add_rownnames works, but rownames_to_column does not

963 Views Asked by At

I have a large dataframe that I summarize using describe to create a new summary dataframe

 df_sum <- describe(df[my_subset])

I check to see that df_sum has row names

has_rownames(df_sum)
[1] TRUE
Browse[2]> rownames(df_sum)
 [1] "Q1"                "Q2"                "Q3"                "Q4"                "Q5"               
 [6] "Q6"                "Q7"                "Q8"                "Q9"                "Q10"              

I now try and turn these row names into a new column

Browse[2]> rownames_to_column(df_sum, var = "Test")
Error in Math.data.frame(list(Test = c("Q1", "Q2", "Q3", "Q4", "Q5", "Q6",  : 
  non-numeric variable(s) in data frame: Test

However, if i used the deprecated function add_rownnames, it works!

Browse[2]> add_rownames(df_sum, var = "Test")
# A tibble: 22 x 14
   Test   vars     n  mean    sd median trimmed   mad   min   max range    skew kurtosis     se
   <chr> <int> <dbl> <dbl> <dbl>  <dbl>   <dbl> <dbl> <dbl> <dbl> <dbl>   <dbl>    <dbl>  <dbl>
 1 Q1        1   963  5.22  2.53      5    5.29  2.97     0    10    10 -0.216    -0.615 0.0814
 2 Q2        2   963  5.50  2.56      6    5.56  2.97     0    10    10 -0.240    -0.656 0.0826
 3 Q3        3   963  4.82  2.72      5    4.83  2.97     0    10    10 -0.0509   -0.860 0.0878
 4 Q4        4   963  4.76  3.03      5    4.73  2.97     0    10    10 -0.0102   -1.05  0.0976
 5 Q5        5   963  5.07  3.10      5    5.08  4.45     0    10    10 -0.0366   -1.16  0.100 
 6 Q6        6   963  4.13  3.18      4    3.97  4.45     0    10    10  0.250    -1.16  0.103 
 7 Q7        7   963  4.89  3.14      5    4.86  4.45     0    10    10  0.0330   -1.19  0.101 
 8 Q8        8   963  1.83  2.71      0    1.29  0        0    10    10  1.41      0.862 0.0872
 9 Q9        9   963  4.56  3.05      5    4.50  2.97     0    10    10  0.0499   -1.08  0.0982
10 Q10      10   963  4.11  2.98      4    3.95  2.97     0    10    10  0.327    -0.931 0.0962

What makes add_rownames work, when rownames_to_column fails with that cryptic error message? What do I need to do to fix rownames_to_column ?

Thanks in advance

Thomas Philips

1

There are 1 best solutions below

0
On

I needed to add as.data.frame to my code.

df_sum <- describe(df[my_subset]) 
> class(df_sum)
[1] "psych"      "describe"   "data.frame"

If I apply rownames_to_column to df_sum, get the error message I mentioned earlier. However, if I type

df_sum <- as.data.frame(describe(df[my_subset])) 
> class(df_sum)
[2] "data.frame"

So if I first write

df_sum <- as.data.frame(describe(df[my_subset])) 

and then apply rownames_to_column to df_sum it works as expected.