我经常遇到这样的数据:
#create dummy data frame
data <- as.data.frame(diag(4))
data[data==0] <- NA
data[2,2] <- NA
data
#V1 V2 V3 V4
#1 1 NA NA NA
#2 NA NA NA NA
#3 NA NA 1 NA
#4 NA NA NA 1
行代表参与者,列 V1 到 V4 代表参与者所处的条件(例如,V1 下的 1 表示该参与者处于条件 1,V4 下的 1 表示该参与者处于条件 4)。旁注:数据不是对称的,因此有更多的参与者分布在 4 个条件下。
我想要的是每个参与者的条件向量:
1 NA 3 4
我写了以下内容,但想知道是否有更有效的方法(即使用更少的代码行)?
#replace entries with condition numbers
cond <- data + matrix(rep(0:3, 4), 4, byrow=TRUE) #add 0 to 1 for condition 1...
#get all unique elements (ignore NAs)
cond <- apply(cond, 1, function(x)unique(x[!is.na(x)]))
#because I ignored NAs just now, cond[2,2] is numeric(0)
#assign NA to all values that are numeric(0)
cond[sapply(cond, function(x) length(x)==0)] <- NA
cond <- unlist(cond)
cond
#[1] 1 NA 3 4