在R中,我有一个包含多列的数据集,其中出现了单词“ true”和“ false”,但是在这些变量id1至id4中的随机位置。变量id1和id4也有一些缺失值(NA)。
id1 <- c('abc', 'false', 198,201)
id2 <- c(763,723,'true',323)
id3 <- c('true', 'def', 223,'hij')
id4 <- c(627,376,237,'false')
df1 <- data.frame(id1,id2,id3,id4)
我想在我的数据框中添加一个变量“ id5”,该变量表示特定行的是或否。我将如何最好地做到这一点?
所需结果:
id1 id2 id3 id4 id5
1 abc 763 true 627 true
2 false 723 def 376 false
3 198 true 223 237 true
4 201 323 hij false false
由于值之一始终存在于我们可以使用的数据中rowSums
。
df1$id5 <- rowSums(df1 == 'true', na.rm = TRUE) > 0
df1
# id1 id2 id3 id4 id5
#1 abc 763 true 627 TRUE
#2 false 723 def 376 FALSE
#3 198 true 223 237 TRUE
#4 201 323 hij false FALSE
我们还可以按行使用apply
:
apply(df1 == 'true', 1, any, na.rm = TRUE)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句