I have this df:
df <- structure(list(a = 1:5, b = 6:10, c = 11:15, d = c("a", "b",
"c", "d", "e"), e = 1:5), row.names = c(NA, -5L), class = c("tbl_df",
"tbl", "data.frame"))
a b c d e
<int> <int> <int> <chr> <int>
1 1 6 11 a 1
2 2 7 12 b 2
3 3 8 13 c 3
4 4 9 14 d 4
5 5 10 15 e 5
rownames_to_column
works:
df %>%
column_to_rownames(var="d") %>%
rownames_to_column(var= "d")
# Output
d a b c e
1 a 1 6 11 1
2 b 2 7 12 2
3 c 3 8 13 3
4 d 4 9 14 4
5 e 5 10 15 5
rownames_to_column
works not properly (gives back the index?)
df %>%
column_to_rownames(var="d") %>%
rowwise() %>%
rownames_to_column(var= "d")
# Output:
d a b c e
<chr> <int> <int> <int> <int>
1 1 1 6 11 1
2 2 2 7 12 2
3 3 3 8 13 3
4 4 4 9 14 4
5 5 5 10 15 5
Why does this behaviour occur?
df
originally is a tibble.When you use
column_to_rownames
it becomes a dataframe since tibbles can't have rownames.Next, when you use
rowwise
the data becomes converted to tibble again and rownames are now lost.So when you do
df2 %>% rownames_to_column(var = 'd')
there are no rownames present hence you get a columnd
with row number.