Rearrange rows in data frame

后端 未结 4 1565
抹茶落季
抹茶落季 2020-12-21 08:33

I have a data frame in R which looks like this with two columns:

ID     phone_number
Mark     866458
Paul     986564
Jack     987543
Mary     523422
<         


        
相关标签:
4条回答
  • 2020-12-21 09:17

    We can transpose the dataframe and then create one vector of values

    data.frame(new_col = c(t(df)))
    
    #  new_col
    #1    Mark
    #2  866458
    #3    Paul
    #4  986564
    #5    Jack
    #6  987543
    #7    Mary
    #8  523422
    

    Another base R option using mapply

    data.frame(new_col = c(mapply(c, df$ID, df$phone_number)))
    
    0 讨论(0)
  • 2020-12-21 09:20

    A longer method with an intermediate df, but may be of some value depending on your full dataset:

    library(tidyverse)
    
    df1 <- df %>% 
      rowid_to_column() %>%
      select(rowid, ID = phone_number) 
    
    df2 <- df %>% 
      rowid_to_column() %>%
      select(rowid, ID) %>%
      rbind(df1) %>% 
      arrange(rowid) %>% 
      select(ID)
    

    result:

      ID    
      <chr> 
    1 Mark  
    2 866458
    3 Paul  
    4 986564
    5 Jack  
    6 987543
    7 Mary  
    8 523422
    
    0 讨论(0)
  • 2020-12-21 09:21

    We can also do

    library(tidyverse)
    pmap(df1, c) %>% 
           unlist %>% 
           tibble(new_col = .)
    
    0 讨论(0)
  • 2020-12-21 09:31

    One possibility with tidyverse:

    df %>%
     rowid_to_column() %>%
     gather(var, val, -rowid) %>%
     arrange(rowid) %>%
     select(val)
    
         val
    1   Mark
    2 866458
    3   Paul
    4 986564
    5   Jack
    6 987543
    7   Mary
    8 523422
    
    0 讨论(0)
提交回复
热议问题