简体   繁体   中英

R - sum values if string contains part of a column

I have the following dataframe:

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
)

Now I would like to sum up the values for each single word. This means the table should look like this:

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

I could not find a solution by now. Does anybody has a solution?

Here's an example using unnest_tokens from the tidytext library:

library(tidyverse)
library(tidytext)

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

You can get all of the words to sum up using strsplit then use sapply to sum up by the word.

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 

One option could be to separate word column in multiple columns using splitstackshape::cSplit and then use tidyr::gather . Finally process data in long format.

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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM