Sex cat dog horse
Male YES NO NO
Female YES YES NO
Male YES YES NO
Female NO NO NO
Male NO NO NO
Male NO YES YES
Female YES YES YES
Female YES NO YES
Male NO NO NO
Male YES NO YES
Male NA NO NO
Female NA NO YES
Female NO YES NO
Female NA NA YES
Female YES NA NO
Male YES NA YES
Male NO NA NO
Male NO NA YES
Male NA NA NA
data$animals <- paste(c(data$cat, data$dog, data$horse), collapse = "")
CrossTable(data$animals,data$sex, prop.chisq = FALSE, prop.t=FALSE, chisq = T)
我目前的数据设置是这样的,而我正在尝试的是将“拥有一个____”中的所有YES,NO和NA合并为一个新列,告诉我“拥有一个动物“并且具有相同的输入(YES,NO或NA)。 我试过“粘贴”,但它似乎没有提供我想要的东西
感谢您提供任何帮助!
我的最终目标是这样的
sex owns animals
Male YES
Female YES
Male YES
Female NA
Male NA
Male NO
Female NO
Female YES
Male YES
Male YES
Male NA
Female NO
Female NO
Female NA
Female YES
Male NO
Male YES
Male NA
Male NA
答案 0 :(得分:5)
df <- read.table(text="Male YES NO NO
Female YES YES NO
Male YES YES NO
Female NO NO NO
Male NO NO NO
Male NO YES YES
Female YES YES YES
Female YES NO YES
Male NO NO NO
Male YES NO YES
Male NA NO NO
Female NA NO YES
Female NO YES NO
Female NA NA YES
Female YES NA NO
Male YES NA YES
Male NO NA NO
Male NO NA YES
Male NA NA NA", header=F)
df$animal <- apply(df[, 2:4], 1, function(x) any(x=="YES"))
df$animal <- ifelse(df$animal, "YES","NO")
df
# V1 V2 V3 V4 animal
# 1 Male YES NO NO YES
# 2 Female YES YES NO YES
# 3 Male YES YES NO YES
# 4 Female NO NO NO NO
# 5 Male NO NO NO NO
# 6 Male NO YES YES YES
# 7 Female YES YES YES YES
# 8 Female YES NO YES YES
# 9 Male NO NO NO NO
# 10 Male YES NO YES YES
# 11 Male <NA> NO NO <NA>
# 12 Female <NA> NO YES YES
# 13 Female NO YES NO YES
# 14 Female <NA> <NA> YES YES
# 15 Female YES <NA> NO YES
# 16 Male YES <NA> YES YES
# 17 Male NO <NA> NO <NA>
# 18 Male NO <NA> YES YES
# 19 Male <NA> <NA> <NA> <NA>