4

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?

starball
  • 20,030
  • 7
  • 43
  • 238
TarJae
  • 72,363
  • 6
  • 19
  • 66
  • Why do you need to do this kind of transformation – akrun May 01 '21 at 18:32
  • Maybe it is ridiculous, but I tried to solve this problem: . I wanted to hide this column and then bring it back after rowwise manipulation. – TarJae May 01 '21 at 18:43
  • For that case, you could still returns a data.frame according to the solution I posted there – akrun May 01 '21 at 18:48

2 Answers2

6

df originally is a tibble.

class(df)
[1] "tbl_df"     "tbl"        "data.frame"

When you use column_to_rownames it becomes a dataframe since tibbles can't have rownames.

df1 <- df %>% column_to_rownames(var="d")
class(df1)
#[1] "data.frame"

Next, when you use rowwise the data becomes converted to tibble again and rownames are now lost.

df2 <- df1 %>% rowwise()
class(df2)
#[1] "rowwise_df" "tbl_df"     "tbl"        "data.frame"

So when you do df2 %>% rownames_to_column(var = 'd') there are no rownames present hence you get a column d with row number.

rownames(df2)
#[1] "1" "2" "3" "4" "5"
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
2

We could create a condition to check before applying the 'rownames_to_column'

library(dplyr)
library(tibble)
df %>%
    column_to_rownames(var = 'd')  %>%
    rowwise %>%
   {if(has_rownames(.)) rownames_to_column(., var = 'd') 
    else .}
akrun
  • 874,273
  • 37
  • 540
  • 662