mutate function dropping row names in r
2
1
Entering edit mode
4.4 years ago
veronico ▴ 70

Hi everyone,

Does anyone know how to fix this: I am using the following code to create certain groupings, but doing so changes my row names to numbers. Is there a way to avoid this, please?

table5[] <- death%>% mutate(Group = case_when(
Mean > 0 ~ "1",
Mean < 0 & Mean > -1 ~ "2",
Mean < -1 & Mean > -1.5 ~ "3",
Mean < -1.5 ~ "4"))

Thank you!

R • 4.3k views
ADD COMMENT
1
Entering edit mode
4.4 years ago
zx8754 11k

Keeping data in rownames is against the philosophy of dplyr (tidyverse). So we need to make extra steps to preserve them, see example:

# using dplyr, need to preserve rownames
death %>% 
  rownames_to_column() %>% 
  mutate(Group = case_when(
    Mean > 0 ~ "1",
    Mean < 0 & Mean > -1 ~ "2",
    Mean < -1 & Mean > -1.5 ~ "3",
    Mean < -1.5 ~ "4")) %>% 
  column_to_rownames()

#    Mean Group
# r1   -3     4
# r2    0  <NA>
# r3    3     1
# r4   -2     4
# r5    1     1
# r6   -1  <NA>
# r7    2     1

Or just use base::cut:

# using base cut, no issues with rownames
death$Group <- cut(death$Mean, c(-Inf, -1.5, -1, 0, Inf))
death   
#    Mean       Group
# r1   -3 (-Inf,-1.5]
# r2    0      (-1,0]
# r3    3    (0, Inf]
# r4   -2 (-Inf,-1.5]
# r5    1    (0, Inf]
# r6   -1   (-1.5,-1]
# r7    2    (0, Inf]
ADD COMMENT
0
Entering edit mode

Thank you so much! This was super helpful!

ADD REPLY
0
Entering edit mode

If this answers you question then consider accepting as an answer.

ADD REPLY
0
Entering edit mode
4.4 years ago
b.bearmi ▴ 10

Can you include a short reproducible example of how your data looks like? If your row order (and number of rows) does not change you could just reassign row names from your death object

ADD COMMENT

Login before adding your answer.

Traffic: 2275 users visited in the last hour
Help About
FAQ
Access RSS
API
Stats

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6