我正在使用ggplot2
电影数据集,我需要创建一个新列"建议"这是评级的结果。因此,例如,要分配的值之一是"跳过"如果评级低于或等于5,"考虑"如果评级介于5.1和8等之间
我不能让我的代码工作。有人可以开导我吗?
mov1$advice<-ifelse(mov1$rating<=5 &
mov1$rating(seq(from=5.1, to=8)) & mov1$rating >=8.1,
"skip",
"consider",
"must_see")
答案 0 :(得分:1)
您可以通过稍微调整代码(添加ifelse
的子级别)来实现:
mov1$advice <- ifelse(mov1$rating <= 5,
"skip",
ifelse(mov1$rating >= 5.1 & mov1$rating <= 8,
"consider",
"must_see"))
答案 1 :(得分:0)
使用data.table
library(data.table)
setDT(mov1)
mov1[, advice := ifelse( rating <= 5, "skip",
ifelse( rating >= 5.1 & rating <= 8, "consider", "must_see"))]
答案 2 :(得分:0)
使用比cut
更清晰的ifelse
,因为这类任务的类别数量会增加。
library(ggplot2movies)
mov1 <- movies
mov1$advice <- cut(mov1$rating, breaks = c(0, 5, 8.1, Inf),
labels = c("skip", "consider", "must_see"),
right = FALSE)
summary(mov1$advice)
skip consider must_see
14235 40481 4072