如果string包含列的一部分,则R - sum值

时间:2018-05-28 11:43:29

标签: r sum

我有以下数据框:

df1 <- data.frame( word = c("house, garden, flower", "flower, red", "garden, tree, forest", "house, window, door, red"),
                  value = c(10,12,20,5),
                  stringsAsFactors = FALSE
)

现在我想总结每个单词的值。这意味着该表应如下所示:

word   | value
house  | 15
garden | 30
flower | 22
...

我现在找不到解决方案。有人有解决方案吗?

3 个答案:

答案 0 :(得分:3)

以下是使用unnest_tokens库中的tidytext的示例:

library(tidyverse)
library(tidytext)

df1 %>% 
  unnest_tokens(word, word) %>% 
  group_by(word) %>% 
  summarize(value = sum(value))

答案 1 :(得分:0)

您可以使用strsplit获取所有单词,然后使用sapply来总结单词。

Words = unique(unlist(strsplit(df1$word, ",\\s*")))
sapply(Words, function(w) sum(df1$value[grep(w, df1$word)]))
 house garden flower    red   tree forest window   door 
    15     30     22     17     20     20      5      5 

答案 2 :(得分:0)

一种选择是使用word分隔多列中的splitstackshape::cSplit列,然后使用tidyr::gather。最后以长格式处理数据。

library(tidyverse)
library(splitstackshape)

df1%>% cSplit("word", sep = ",", stripWhite = TRUE) %>%
  mutate_at(vars(starts_with("word")), funs(as.character)) %>%
  gather(key, word, -value) %>%
  filter(!is.na(word)) %>%
  group_by(word) %>% 
  summarise(value = sum(value)) %>%
  as.data.frame()


#     word value
# 1   door     5
# 2 flower    22
# 3 forest    20
# 4 garden    30
# 5  house    15
# 6    red    17
# 7   tree    20
# 8 window     5