rownames_to_column does not work after rowwise() properly
Asked Answered
S

2

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?

Sexless answered 1/5, 2021 at 14:3 Comment(3)
Why do you need to do this kind of transformationAzarria
Maybe it is ridiculous, but I tried to solve this problem: <#67347890>. I wanted to hide this column and then bring it back after rowwise manipulation.Sexless
For that case, you could still returns a data.frame according to the solution I posted thereAzarria
S
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"
Speaker answered 1/5, 2021 at 14:10 Comment(0)
A
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 .}
Azarria answered 1/5, 2021 at 17:29 Comment(3)
So, doesn't ungroup un-does the rowwise??Cateran
Thank you akrun. I already voted up your first answer hereSexless
@Sexless I posted a solution in your other questionAzarria

© 2022 - 2024 — McMap. All rights reserved.