我经常遇到这样的数据:
#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
答案 0 :(得分:2)
我们可以将max.col
与ties.method='first'
一起用于数据&#39;中非NA元素的逻辑矩阵。为了使仅包含NA元素的行为NA,我们将max.col
索引与逻辑矩阵的rowSums
相乘,并将0个非NA行转换为NA(NA^
)。
max.col(!is.na(data), 'first')* NA^!rowSums(!is.na(data))
#[1] 1 NA 3 4
或另一个选项是pmax
。我们将列索引与数据相乘,以便非NA元素被索引替换。然后,将pmax
与na.rm=TRUE
一起使用,并获得每行的最大值。
do.call(pmax, c(col(data)*data, na.rm=TRUE))
#[1] 1 NA 3 4
答案 1 :(得分:1)
使用reshape2
包:
> data$ID <- rownames(data)
> melt(data, 'ID', na.rm=TRUE)
ID variable value
1 1 V1 1
11 3 V3 1
16 4 V4 1
恕我直言,这有利于保持ID变量和治疗因子;如果你有一个响应测量,它也会出现在值列中。
编辑:
如果要在无条件下包含主题,可以明确重建该指标变量:
data$VNA <- ifelse(apply(is.na(data), 1, all), 1, NA)
答案 2 :(得分:1)
比其他解决方案更聪明,更有效,但可能更具可读性?
country_code_to_find = "US"
if user.rules.where("countries @> '[{\"country_code\": \"#{country_code_to_find}\"}]'").exists?
# Do some stuff
end