简体   繁体   中英

How apply dplyr functions into a list-column?

My list-column :

library(tidyverse)

dataset<-as_tibble(matrix(rnorm(6*30,1000,100),ncol=6))
cluster<-kmeans(dataset,centers=3)
dataset$kmeans<-as.factor(cluster[['cluster']])
mylist<-split(dataset,dataset$kmeans)
names(mylist)<-str_c('dataset',seq_along(mylist))

obj<-dataset%>%
  group_by(kmeans)%>%
  nest()

I try:

obj%>%
  summarise_if(.data,is.numeric,sum)

Error: Can't convert a list to function

and

obj%>%
  map(~summarise_if(.data,is.numeric,sum))

Error in UseMethod("tbl_vars") : no applicable method for 'tbl_vars' applied to an object of class "rlang_data_pronoun"

among other attempts...

So, how do I apply dplyr functions into a list-column ?

A solution is use dplyr::pull in list-column ( obj$data ):

library(tidyverse)

obj%>%
  pull(data)%>%
  map(~summarise_if(.,is.numeric,sum))

[[1]]
# A tibble: 1 x 6
      V1     V2     V3     V4     V5     V6
   <dbl>  <dbl>  <dbl>  <dbl>  <dbl>  <dbl>
1 12865. 11787. 12864. 13443. 12548. 13170.

[[2]]
# A tibble: 1 x 6
      V1     V2     V3     V4     V5     V6
   <dbl>  <dbl>  <dbl>  <dbl>  <dbl>  <dbl>
1 11655. 12197. 11379. 10023. 10659. 11154.

[[3]]
# A tibble: 1 x 6
     V1    V2    V3    V4    V5    V6
  <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 5175. 6053. 6855. 6130. 6504. 5967.

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