Reputation: 183
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
Upvotes: 0
Views: 746
Reputation: 887148
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
df <- structure(list(abc = c("efg", "hij")), class = "data.frame",
row.names = c(NA,
-2L))
Upvotes: 0
Reputation: 388982
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
Upvotes: 1