簡體   English   中英

獲取列名稱,並使用r將其指定為數據框中未列出列的值

[英]Get the column name and assign as value in unlisted column in the dataframe using r

我有看起來像這樣的數據框:

   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

感謝您的幫助。

怎么樣:

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 ,如果變量是因素,則必須首先將其轉換為字符串。

您可以嘗試這樣的事情:

# 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))))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM