rownames_to_column does not work after rowwise() properly

800 views Asked by At

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?

2

There are 2 answers

0
Ronak Shah On BEST ANSWER

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"
3
akrun On

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 .}