私はデータフレームを持っています
test <- structure(list(
y2002 = c("freshman","freshman","freshman","sophomore","sophomore","senior"),
y2003 = c("freshman","junior","junior","sophomore","sophomore","senior"),
y2004 = c("junior","sophomore","sophomore","senior","senior",NA),
y2005 = c("senior","senior","senior",NA, NA, NA)),
.Names = c("2002","2003","2004","2005"),
row.names = c(c(1:6)),
class = "data.frame")
> test
2002 2003 2004 2005
1 freshman freshman junior senior
2 freshman junior sophomore senior
3 freshman junior sophomore senior
4 sophomore sophomore senior <NA>
5 sophomore sophomore senior <NA>
6 senior senior <NA> <NA>
そして、データを調整して、次のように、各行の個々のステップのみを取得したいと思います。
result <- structure(list(
y2002 = c("freshman","freshman","freshman","sophomore","sophomore","senior"),
y2003 = c("junior","junior","junior","senior","senior",NA),
y2004 = c("senior","sophomore","sophomore",NA,NA,NA),
y2005 = c(NA,"senior","senior",NA, NA, NA)),
.Names = c("1","2","3","4"),
row.names = c(c(1:6)),
class = "data.frame")
> result
1 2 3 4
1 freshman junior senior <NA>
2 freshman junior sophomore senior
3 freshman junior sophomore senior
4 sophomore senior <NA> <NA>
5 sophomore senior <NA> <NA>
6 senior <NA> <NA> <NA>
各行をベクトルとして扱うと、次のようなことができることを知っています。
careerrow <- c(1,2,3,3,4)
pairz <- lapply(careerrow,function(i){c(careerrow[i],careerrow[i+1])})
uniquepairz <- careerrow[sapply(pairz,function(x){x[1]!=x[2]})]
私の難しさは、それを行ごとにデータテーブルに適用することです。lapplyが進むべき道だと思いますが、今のところこれを解決することはできません。