Home > front end >  Replace integers in a data frame column with other integers in R?
Replace integers in a data frame column with other integers in R?

Time:05-18

I want to replace a vector in a dataframe that contains only 4 numbers to specific numbers as shown below

tt <- rep(c(1,2,3,4), each = 10)
df <- data.frame(tt)

I want to replace 1 = 10; 2 = 200, 3 = 458, 4 = -0.1

CodePudding user response:

You could use recode from dplyr. Note that the old values are written as character. And the new values are integers since the original column was integer:

library(tidyverse):
df %>% 
   mutate(tt = recode(tt, '1'= 10, '2' = 200, '3' = 458, '4' = -0.1))

     tt
1  10.0
2  10.0
3 200.0
4 200.0
5 458.0
6 458.0
7  -0.1
8  -0.1

CodePudding user response:

1) To correct the error in the code in the question and provide for a shorter example we use the input in the Note at the end. To get the result since the input is 1 to 4 we can use indexing:

nos <- c(10, 200, 458, -0.1)
transform(df, tt = nos[tt])
##      tt
## 1  10.0
## 2  10.0
## 3 200.0
## 4 200.0
## 5 458.0
## 6 458.0
## 7  -0.1
## 8  -0.1

2) Another approach is to use arithmetic:

transform(df, tt = 10 * (tt == 1)   
                   200 * (tt == 2)   
                   458 * (tt == 3)  
                   -0.1 * (tt == 4))

3) This would also work:

transform(df, tt = c(outer(tt, 1:4, `==`) %*% nos))

Note

df <- data.frame(tt = c(1, 1, 2, 2, 3, 3, 4, 4))
  • Related