简体   繁体   中英

How to add row to a dataframe with a pipe using tidyverse?

Example

Consider this dataframe

 abc
 efg
 hij

(abc is the column)

I want to convert this into

 X
 abc
 efg
 hij

Where X is now the main column name and abc is in the values

I tried this

 df %>% mutate(X = abc)

this turns it into

X
efg
hij

with abc disappearing

In case you have multiple columns, you can do :

library(dplyr)

names(df) %>%
  t %>%
  as.data.frame() %>%
  setNames(names(df)) %>%
  bind_rows(df) %>%
  rename_all(~LETTERS[seq_len(ncol(df))])

#    A
#1 abc
#2 efg
#3 hij

For only single column, it could be simplified a bit.

names(df) %>%
  setNames(names(df)) %>%
  bind_rows(df) %>%
  rename(X = abc)

#  X    
# <chr>
#1 abc  
#2 efg  
#3 hij  

We can also use imap to do the appending of column names

library(dplyr)
library(purrr)
imap_dfr(df, ~ c(.y, .x)) %>% 
      rename_all(~ 'X')
# A tibble: 3 x 1
#  X    
#  <chr>
#1 abc  
#2 efg  
#3 hij  

data

df <- structure(list(abc = c("efg", "hij")), class = "data.frame", 
     row.names = c(NA, 
-2L))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM