作为R中的新手,如何正确处理具有多个值的变量:
x = c("1","1","1/2","2","2/3","1/3")
如您所见,价值3仅与其他人联合出现。
要进一步计算x
,最好的方法是获得3个向量,如:
X[1] = c(1,1,1,NA,NA,1)
因为“1”出现在第1,第2,第3和第6位。
同意X[2]
和X[3]
所有信息似乎都保留了下来:我错了吗?
我已经测试了strsplit,但它没有保留{vector}中尚未存在的NA
值。
答案 0 :(得分:2)
另一种方法是使用我的" splitstackshape"中的cSplit_e
。封装
x = c("1","1","1/2","2","2/3","1/3")
library(splitstackshape)
cSplit_e(data.frame(x), "x", "/")
# x x_1 x_2 x_3
# 1 1 1 NA NA
# 2 1 1 NA NA
# 3 1/2 1 1 NA
# 4 2 NA 1 NA
# 5 2/3 NA 1 1
# 6 1/3 1 NA 1
(请注意,此处的结果与已接受答案中的结果进行比较。)
答案 1 :(得分:0)
这似乎有效:
x = c("1","1","1/2","2","2/3","1/3")
#Split on your character. This may not be inclusive of all characters that
#need to be split on.
xsplit <- strsplit(x, "\\/")
#Find the unique items
xunique <- unique(unlist(xsplit))
#Iterate over each xsplit for all unique values
out <- sapply(xsplit, function(z)
sapply(xunique, function(zz) zz %in% z)
)
#convert FALSE to NA
out[out == FALSE] <- NA
#Results in
> out
[,1] [,2] [,3] [,4] [,5] [,6]
1 TRUE TRUE TRUE NA NA TRUE
2 NA NA TRUE TRUE TRUE NA
3 NA NA NA NA TRUE TRUE