Thank you so much! This was super helpful!
• 0 views
•
link
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!
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]
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
Log in to answer this question.