【发布时间】:2016-11-29 12:33:05
【问题描述】:
假设我有一个数据框:
word <- c("good", "great", "bad", "poor", "eh")
userid <- c(1, 2, 3, 4, 5)
d <- data.frame(userid, word)
我想添加一个数据框列sentiment,它是一个factor,取决于word 是什么:
words_pos <- c("good", "great")
words_neg <- c("bad", "poor")
calculate_sentiment <- function(x) {
if (x %in% words_pos) {
return("pos")
} else if (x %in% words_neg) {
return("neg")
}
return(NA)
}
d$sentiment <- apply(d, 1, function(x) calculate_sentiment(x['word'])
但是,现在d$sentiment 属于“字符”类型。我如何使它成为具有正确水平的因素? pos, neg, NA -- 我什至不确定NA 是否应该是一个因子水平,因为我正在学习 R。
谢谢!
【问题讨论】:
-
试试:d$sentiment
-
如果只需要单列,请不要申请。这既危险(因为矩阵转换)又非常低效。而且我认为您正在寻找
addNA而不是factor。像addNA(sapply(word, calculate_sentiment))这样的东西。更不用说您可能也可以轻松地对其进行矢量化。
标签: r