5

我的目标和背景

我在 R 中有一个数据框,我想使用 reshape2 库来融化它。有两个原因。

  1. 我想使用 ggplot 在条形图中为每个用户绘制每个问题的分数。

  2. 我想把这些数据放到 Excel 中,这样我就可以看到每个用户的情绪、分数和混合动机、态度之前等。我的意图是使用融化,然后将数据转换为宽格式,以便于 Excel 导入.

我的问题

当我尝试运行 melt 时,我收到警告并在生成的熔融数据框中出现 NA。

Warning messages:
1: In `[<-.factor`(`*tmp*`, ri, value = c(0.148024, 0.244452, -0.00421,  :
invalid factor level, NAs generated
2: In `[<-.factor`(`*tmp*`, ri, value = c(0L, 0L, 0L, 0L, 0L, 0L, 0L,  :
invalid factor level, NAs generated

我最终在我得到的融化数据框中得到了大量的 NA。我认为这是因为我在同一列中同时使用字符和数字。

我的问题

结果我有两个问题。

问题 1:在 R 中有解决方法吗?

问题 2:我有没有更好的方法来构建我的数据以避免这个问题?

代码

这是我创建数据框的代码。

words <- data.frame(read.delim("sentiments-test-subset-no-text.txt", header=FALSE))
names(words) <- c("level", "question", "user", "sentiment", "score", "mixed")
words$user <- as.factor(words$user)
words.m <- melt(words, id.vars=c("user", "level"), measure.vars=c("sentiment", "score",     "mixed"))

我对重塑和融化很陌生,但我认为这就是我在最后一行想要的。

数据

人类可读格式的数据如下所示。

experimental    motivated   1   positive    0.148024    0
experimental    motivated   2   positive    0.244452    0
experimental    motivated   3   negative       -0.004210    0
experimental    motivated   4   unknown         0.000000    0
experimental    attitudeBefore  1   negative       -0.241500    0
experimental    attitudeBefore  2   neutral         0.000000    0
experimental    attitudeBefore  3   neutral         0.000000    0
experimental    attitudeBefore  4   unknown         0.000000    0

输出转储

dput 下面。

structure(list(level = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L), .Label = "experimental", class = "factor"), question = structure(c(2L, 
2L, 2L, 2L, 1L, 1L, 1L, 1L), .Label = c("attitudeBefore", "motivated"
), class = "factor"), user = structure(c(1L, 2L, 3L, 4L, 1L, 
2L, 3L, 4L), .Label = c("1", "2", "3", "4"), class = "factor"), 
sentiment = structure(c(3L, 3L, 1L, 4L, 1L, 2L, 2L, 4L), .Label = c("negative", 
"neutral", "positive", "unknown"), class = "factor"), score = c(0.148024, 
0.244452, -0.00421, 0, -0.2415, 0, 0, 0), mixed = c(0L, 0L, 
0L, 0L, 0L, 0L, 0L, 0L)), .Names = c("level", "question", 
"user", "sentiment", "score", "mixed"), row.names = c(NA, -8L
), class = "data.frame")
4

1 回答 1

4

看起来您可能只是使用了错误的库。 reshapereshape2不是一回事。

library(reshape2)
words.m <- melt(words, id.vars=c("user", "level"), measure.vars=c("sentiment", "score",     "mixed"))
# no problem

detach(package:reshape2)

# using reshape instead of reshape2
library(reshape)
words.m <- melt(words, id.vars=c("user", "level"), measure.vars=c("sentiment", "score",     "mixed"))
# Warning messages:
# 1: In `[<-.factor`(`*tmp*`, ri, value = c(3L, 3L, 1L, 4L, 1L, 2L, 2L,  :
#   invalid factor level, NAs generated
# 2: In `[<-.factor`(`*tmp*`, ri, value = c(3L, 3L, 1L, 4L, 1L, 2L, 2L,  :
#   invalid factor level, NAs generated

如果reshape2在您的系统上不可用,您可以从 CRAN 安装它

 install.packages("reshape2")
于 2013-04-12T16:38:01.037 回答