r-convert list column into character vector where lists are characters

末鹿安然 提交于 2020-06-16 15:15:12

问题


I'm trying to convert a list into a single character value, or basically go from this:

test <- data.frame(a = c(1,1,1,2,2,2), b = c("a", "b", "c", "d", "e", "f" )) %>% 
  group_by(a) %>% summarise(b = list(b))

to this:

test <- data.frame(a = c(1,2), b = c("a, b, c", "d, e, f" )) 

回答1:


Here you go:

test %>% 
  mutate(b = sapply(b, toString))

## A tibble: 2 x 2
#      a b      
#  <dbl> <chr>  
#1    1. a, b, c
#2    2. d, e, f



回答2:


As suggested by the OP, I post my comment as an answer for future reference.

Starting from the raw data frame, you can do:

data.frame(a = c(1,1,1,2,2,2), b = c("a", "b", "c", "d", "e", "f")) %>% 
   group_by(a) %>%
   summarise(b = paste(b, collapse = ","))

## A tibble: 2 x 2
#      a b    
#  <dbl> <chr>
#1  1.00 a,b,c
#2  2.00 d,e,f


来源:https://stackoverflow.com/questions/50174438/r-convert-list-column-into-character-vector-where-lists-are-characters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!