Reputation: 327
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?
Upvotes: 1
Views: 2461
Reputation: 20095
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
Upvotes: 0
Reputation: 783
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))
Upvotes: 3
Reputation: 37651
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
Upvotes: 0