How to add new column from list column value

后端 未结 2 1625
暖寄归人
暖寄归人 2020-12-21 07:29

How to unlist list column and add new column from unlist column value in data frame.Can you please find my df below.

My data Frame.

Status       Audi         


        
相关标签:
2条回答
  • 2020-12-21 07:56

    As each of the list columns has a different structure, you'll have to deal with them in different ways.

    With base R:

    dfnew <- data.frame(df$Status,
                        do.call(rbind, lapply(df$AuditResult, function(x) sapply(x, toString))),
                        do.call(rbind, df$Deship),
                        do.call(rbind, lapply(df$Item, unlist)))
    names(dfnew) <- sub('^.*\\.','',names(dfnew))
    

    which gives:

    > dfnew
        Status      DDID   Dvalue UserID        Add Menu Bill IDesc vendor
    1   Active  2, First Bpin, 67      1 Stet, Bpin    1    9     A      5
    2 Inactive Second, 8   CA, 98      2 Stet, Bpin    1    8 B,N,O      4
    3   OnHold 78, 8, NA   UK, 76      1 Stet, Bpin    1    7   L,q      2
    
    0 讨论(0)
  • 2020-12-21 08:13

    Assuming that the name of your data frame is called dt, here is an option.

    library(tidyverse)
    
    dt2 <- dt %>%
      select(Status, AuditResult) %>%
      mutate(DDID = map(AuditResult, ~.$DDID),
             Dvalue = map(AuditResult, ~.$Dvalue)) %>%
      mutate(DDID = map_chr(DDID, ~toString(.)),
             Dvalue = map_chr(Dvalue, ~toString(.))) %>%
      select(-AuditResult)
    
    dt3 <- dt %>%
      select(Status, Deship) %>%
      unnest()
    
    dt4 <- dt %>%
      select(Status, Item) %>%
      unnest() %>%
      unnest()
    
    dt_final <- reduce(list(dt2, dt3, dt4), left_join, by = "Status")
    dt_final
    #     Status      DDID   Dvalue UserID        Add Menu Bill IDesc vendor
    # 1   Active  2, First Bpin, 67      1 Stet, Bpin    1    9     A      5
    # 2 Inactive Second, 8   CA, 98      2 Stet, Bpin    1    8 B,N,O      4
    # 3   OnHold 78, 8, NA   UK, 76      1 Stet, Bpin    1    7   L,q      2
    
    0 讨论(0)
提交回复
热议问题