Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
157 views
in Technique[技术] by (71.8m points)

r - How to build subset with looping codes using unique ID

I try to write a looping code with ID in a data.frame df. what I did right now is I build another list dm which contains the unique ID from df$ID:

dm<-df %>% select(ID) %>% unique()
for (i in 1:length( dm$ID)){
   df_new<-df %>% filter(ID %in% dm$ID[i]) 
...

Current codes can do what I need. But I wonder whether there is another way to do it without building dm? I want to build subset by each ID in df. Any suggestion?

question from:https://stackoverflow.com/questions/65891339/how-to-build-subset-with-looping-codes-using-unique-id

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Instead of looping over the unique 'ID' and subseting, a faster option is split which will split the data.frame into list of data.frame based on the unique values of 'ID'

df_list <- split(df, df$ID)     

From here, we can either use lapply or a for loop

pdf(paste0(out_dir, output_date,'.pdf')) 
for(i in seq_along(df_list)) {
     ggplot(data = df_list[[i]]) + 
           ...
    } 
dev.off()

Or with lapply

pdf(paste0(out_dir, output_date,'.pdf'))    
lapply(df_list, function(dat) 
        ggplot(data = dat) + 
           ...
    )
dev.off()        

Regarding the creation of an object of unique 'ID', a better option is

for(un in unique(df$ID)) {
       df_new <- df %>%
                    filter(ID == un)
       ggplot(df_new) + 
           ...
  }      

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...