我有一个大约1000列的数据框。我对14个满意度等级变量感兴趣。
我需要删除14个评分变量中的任何一个包含“项目已跳过”或不适用的行。
有没有一种方法可以删除在我的满意满意度矢量变量中出现NA或“项目已跳过”的所有行,当前在矢量“ cols”中。在下面的示例中,“ cols”包含服务,效率和风味,但不包含经验和质量
cols = c("Service","Efficiency","Flavour")
dat<-data.frame(Number = 1:6, University = c("A","B","C","D","E","F"),
Service=c("Satisfied","Item skipped",NA, "Not satisfied", "Neither","Item skipped" ),
Efficiency =c("Neither", "Neither", "Item skipped","Satisfied", NA, NA),
Flavour =c("Satisfied", NA, "Item skipped",
"Neither", NA, NA), Quality =c("Not satisfied", "Neither", NA,"Satisfied", NA, NA),
Experience =c("Satisfied", NA, NA,
"Not satisfied", NA, NA),Age =rep(c(18:19), times =3))
答案 0 :(得分:2)
在基数R中,我们可以使用rowSums
删除NA
中出现“项目跳过”或cols
的行
cols = c("Service", "Efficiency", "Flavour")
dat[rowSums(dat[cols] == "Item skipped" | is.na(dat[cols])) == 0, ]
# Number University Service Efficiency Flavour Quality Experience Age
#1 1 A Satisfied Neither Satisfied Not satisfied Satisfied 18
#4 4 D Not satisfied Satisfied Neither Satisfied Not satisfied 19
@amrrs建议使用apply
的替代方法
dat[!apply(dat[cols], 1, function(x) any(x == 'Item skipped' | is.na(x))), ]
答案 1 :(得分:0)
编辑:: 我们可以使用更新的数据(这是基于NA总是与“ Item_Skipped”一起出现的情况):
dat %>%
filter(!is.na(Experience))
Number University Service Efficiency Flavour Quality Experience Age
1 1 A Satisfied Neither Satisfied Not satisfied Satisfied 18
2 4 D Not satisfied Satisfied Neither Satisfied Not satisfied 19
原件::
我们可以使用(以下注释中的数据):
dat %>%
filter_at(vars(contains("rating")),all_vars(.!="Item Skipped"))
OR ::
dat %>%
filter_all(all_vars(.!="Item Skipped"))
输出:
Number University Service_rating Efficiency_rating Flavour_rating Age
1 1 A Satisfied Neither Satisfied 18
2 4 D Not satisfied Satisfied Neither 19
注意:
dat<-data.frame(Number = 1:6, University = c("A","B","C","D","E","F"),
Service_rating=c("Satisfied","Item skipped",NA, "Not satisfied", "Neither","Item skipped" ),
Efficiency_rating =c("Neither", "Neither", "Item skipped","Satisfied", NA, NA),
Flavour_rating =c("Satisfied", NA, "Item skipped",
"Neither", NA, NA), Age =rep(c(18:19), times =3))