Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to recode values in a column in R?

I have the following data, where I have calculated the tercile for each value in x:

dc <- data.frame(x = c(1, 2, 5, 6, 8, 9))
dc$tercile <- fabricatr::split_quantile(dc$x, 3)

x tercile
1       1
2       1
5       2
6       2
8       3
9       3

I want to reflect the ranges in x for each tercile. The desired output:

x       tercile
1    period 1-2
2    period 1-2
5    period 5-6
6    period 5-6
8    period 8-9
9    period 8-9

A tidyverse solution is preferred. Thanks!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use sprintf() or paste() by groups of tercile.

library(dplyr)

dc %>%
  mutate(range = sprintf("period %d-%d", min(x), max(x)),
         .by = tercile)

#   x tercile      range
# 1 1       1 period 1-2
# 2 2       1 period 1-2
# 3 5       2 period 5-6
# 4 6       2 period 5-6
# 5 8       3 period 8-9
# 6 9       3 period 8-9
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading