Home > Net >  How to replace values in R dataframe without overwriting?
How to replace values in R dataframe without overwriting?

Time:06-14

Given this example dataframe

> Name <- c("Jon", "Bill", "Maria", "Ben", "Tina", "Sam")
> Age <- c(11, 12, 13, 21, 22, 23)
> 
> df <- data.frame(Name, Age)
> df
   Name Age
1   Jon  11
2  Bill  12
3 Maria  13
4   Ben  21
5  Tina  22
6   Sam  23

How can I replace the Age values in a way, such that the result dataframe is

   Name Age
1   Jon  21
2  Bill  22
3 Maria  23
4   Ben  11
5  Tina  12
6   Sam  13

My difficulty is avoiding to overwrite the already replaced values, e.g.

> df <- df %>% mutate(Age = replace(Age, Age == "11", "21"), Age = replace(Age, Age == "21", "11"))
> df
   Name Age
1   Jon  11
2  Bill  12
3 Maria  13
4   Ben  11
5  Tina  22
6   Sam  23

CodePudding user response:

So you want to replace all ages that start with 1 to 2, and 2 to 1? If so, here is my suggestion:

df <- tibble(
  name = c("Jon", "Bill", "Maria", "Ben", "Tina", "Sam"),
  age = c(11, 12, 13, 21, 22, 23) %>% as.character()
)

# A tibble: 6 x 2
  name  age  
  <chr> <chr>
1 Jon   11   
2 Bill  12   
3 Maria 13   
4 Ben   21   
5 Tina  22   
6 Sam   23  

The code

df %>%  
  mutate(age = 
           case_when(
             str_detect(age, "^1")  ~ str_replace(age, "1", "2"),
             str_detect(age, "^2") ~ str_replace(age, "2", "1"),
             TRUE ~ age) %>%  
           as.double()
         )


# A tibble: 6 x 2
  name    age
  <chr> <dbl>
1 Jon      21
2 Bill     22
3 Maria    23
4 Ben      11
5 Tina     12
6 Sam      13

CodePudding user response:

Using base R with chartr

with(df, as.integer(paste0(chartr('12', '21', Age %/% 10), substr(Age, 2, 2))))
[1] 21 22 23 11 12 13
  • Related