How to flatten R data frame that contains lists?

后端 未结 3 2015
梦谈多话
梦谈多话 2020-12-17 15:08

I want to find the best \"R way\" to flatten a dataframe that looks like this:

  CAT    COUNT     TREAT
   A     1,2,3     Treat-a, Treat-b
   B     4,5              


        
3条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-17 15:57

    Here is another way in base r

    df<-data.frame(CAT=c("A","B"))
    df$COUNT <-list(1:3,4:5)
    df$TREAT <-list(paste("Treat-", letters[1:2],sep=""),paste("Treat-", letters[3:5],sep=""))
    

    Create a helper function to do the work

    f <- function(l) {
      if (!is.list(l)) return(l)
      do.call('rbind', lapply(l, function(x) `length<-`(x, max(lengths(l)))))
    }
    

    Always test your code

    f(df$TREAT)
    
    #           [,1]      [,2]      [,3]     
    # [1,] "Treat-a" "Treat-b" NA       
    # [2,] "Treat-c" "Treat-d" "Treat-e"
    

    Apply it

    df[] <- lapply(df, f)
    df
    
    #     CAT COUNT.1 COUNT.2 COUNT.3 TREAT.1 TREAT.2 TREAT.3
    #   1   A       1       2       3 Treat-a Treat-b    
    #   2   B       4       5      NA Treat-c Treat-d Treat-e
    

提交回复
热议问题