Home > front end >  Replace multiple similar values in a column in R
Replace multiple similar values in a column in R

Time:12-12

I have a data frame with deidentified information that looks like this

Gender    Age   Score
 Male      2      7
 Male      6      1
 Male      5      5
 Male      3      9
 Female    9      11
 Female    12      11
 Female    6      11

I would like to replace all the 2's with "5 years old" and all the 3's with "6 years old" and so on.

I can use this

data$Age[data$Age ==2] <- 5 years old

but I have data ranging from 5 years to 25 years old and to repeat that 20 times is not exactly appealing.

I would like a function to iterate from 2 all the way to 22.

Is there an easier way of doing this?

Thanks

CodePudding user response:

Perhaps adding 3 and pasting " years old" will satisfy your needs?

 data$txtAge <- paste(data$Age, "years old")

There is no need for an iterative command. R's functions often iterate automagically. In this case the paste command is designed to return character results of the same length as the longest input argument but it "recycles" (repeats) the shorter argument. You would get a column of the same length as there were rows in the data object.

CodePudding user response:

Like IRTFM said, you have to add 3 and paste the "years old" string. You're getting an error regarding non-numeric arguments to binary operators because you're trying to add a number to a character string.

So, let's be a little more explicit: you have to add 3 first, and then paste the "years old" string (you're doing it in the wrong order).

  • Related