获取列名称,并使用r将其指定为数据框中未列出列的值

时间:2019-02-25 16:30:32

标签: r dataframe

我有一个看起来像这样的数据框:

   negative     positive
1:              enjoyed
2: hate         famous,helpful
3: forget,poor
4: hate         enjoyed, kind

我想将其转换为如下形式:

  text     sentiment
1 hate     negative
2 forget   negative
3 poor     negative
4 enjoyed  positive
5 famous   positive
6 helpful  positive
7 kind     positive

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

怎么样?

df0 <- data.frame(
  negative = c("", "hate", "forget,poor", "hate"),
  positive = c("enjoyed", "famous,helpful", "", "enjoyed, kind"), 
  stringsAsFactors = FALSE
)

values <- sapply(df0, function(x) unique(trimws(unlist(strsplit(x, ",")))))

df1 <- data.frame(
  text = unlist(values),
  sentiment = rep(c("negative", "positive"), lengths(values)), 
  row.names = NULL
)
df1

请注意,我使用了stringsAsFactors = FALSE,如果您的变量是因素,则必须先将其转换为字符串。

答案 1 :(得分:1)

您可以尝试这样的事情:

# create testdat
test_data <- data.frame(negative = c("", "hate", "forget, poor", "hate"), positive = c("enjoyed", "famous, helpful", "", "enjoyed, kind"), stringsAsFactors = F)

#extract positive and negative colum and split along ", "
neg <- unique(unlist(strsplit(test_data$negative, ", ")))
pos <- unique(unlist(strsplit(test_data$positive, ", ")))

# combine neg and positive into a dataframe and add the sentiment column
combined <- data.frame(text = c(pos, neg), sentiment = c(rep("positive", length(pos)), rep("negative", length(neg))))