neves
neves

Reputation: 846

How to keep group column in each tibble and rename them?

I have the follow list-column called my$data:

library(tidyverse)

dataset<-data.frame(matrix(rnorm(6*30,1000,100),ncol=6))
cluster<-kmeans(dataset,centers=3)
dataset$kmeans<-as.factor(cluster[['cluster']])

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

I have two doubts:

With base::split function, the group column is preserved. Example:

mylist<-split(dataset,dataset$kmeans)

And base::names function:

names(mylist)<-paste0('data',seq_along(mylist))

Upvotes: 1

Views: 161

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389135

Not sure if it is possible to have the grouped column in nest however, an alternative is to create a copy of the column and then use nest.

library(tidyverse)

mydata <- dataset %>%
              mutate(new_kmean = kmeans) %>%
              group_by(kmeans) %>%
              nest()

names(mydata$data) <- paste0('data',seq_along(mydata$data))


mydata$data

#$data1
# A tibble: 16 x 7
#    X1    X2    X3    X4    X5    X6 new_kmean
#   <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <fct>    
# 1  952. 1057. 1037. 1049.  871. 1103. 3        
# 2 1042.  986. 1027.  982.  836. 1121. 3        
# 3  990.  996. 1121. 1134.  998. 1098. 3 
#....      

Upvotes: 1

Related Questions