R: Count unique words in a column with multiple words in each cell

If I have several columns with several words inside a factor (separated by ",") in each cell. How can I get a list of unique words for each column? For example:

    var1 | var2 | var3
    a,b  | a,b  | a,c
    a,x  | b,s  | d,s
    a,d  | b,m  | e,m

And I would like to get the result in a list / data format:

      var1     |   var2     |   var3
    [a,b,d,x]  | [a,b,s,m]  | [a,c,d,s,e,m]
+4
source share
2 answers

You can do this with strsplit+ uniquein the instructions lapply:

lapply(mydf, function(x) unique(trimws(unlist(strsplit(x, ",")))))
## $var1
## [1] "a" "b" "x" "d"
## 
## $var2
## [1] "a" "b" "s" "m"
## 
## $var3
## [1] "a" "c" "d" "s" "e" "m"
## 

If you need one line as a result, add there toString, and you can wrap it all in data.frameto get data.frameinstead list:

data.frame(lapply(mydf, function(x) toString(unique(trimws(unlist(strsplit(x, ",")))))))
##         var1       var2             var3
## 1 a, b, x, d a, b, s, m a, c, d, s, e, m

, sprintf + paste. , lapply "temp", :

lapply(temp, function(x) sprintf("[%s]", paste(x, collapse = ",")))
## $var1
## [1] "[a,b,x,d]"
## 
## $var2
## [1] "[a,b,s,m]"
## 
## $var3
## [1] "[a,c,d,s,e,m]"
## 
+5

:

library(dplyr)

data = 
  data_frame(
    var1 = list(c("a", "b"),
                c("a", "x") ),
    var2 = list(c("a", "b"),
                c("b", "s") ) )

long_data = 
  data %>%
  as.list %>%
  lapply(. %>% 
           lapply(. %>% 
                    data_frame(value = .) ) %>%
           bind_rows(.id = "row") ) %>%
  bind_rows(.id = "column") %>%
  group_by(column, row) %>%
  mutate(order = 1:n() )

long_data %>%
  select(-row) %>%
  distinct
+1

Source: https://habr.com/ru/post/1617683/


All Articles