0

I'm currently an R novice and have come across an issue while recoding variables in my dataset. I would really appreciate any advice you may have on this issue. I have several different "education_code" variables that contain information about a given individual's educational qualifications.

#create simulated data
df = data.frame(ID = c(1001,1002,1003,1004, 1005,1006,1007,1008,1009,1010,1011),
                    education_code_1 = c('1','2','1','1','NA', '5', '2', '3', 'NA','2','5'),
                    education_code_2 = c('2','4','3','4','5', '2','1','2','5','1','3'),
                    education_code_3 = c('3', '3','NA', '4','2', '1','NA','3','4','NA','2'))

Which looks like this:

     ID education_code_1 education_code_2 education_code_3
1  1001                1                2                3
2  1002                2                4                3
3  1003                1                3               NA
4  1004                1                4                4
5  1005               NA                5                2
6  1006                5                2                1
7  1007                2                1               NA
8  1008                3                2                3
9  1009               NA                5                4
10 1010                2                1               NA
11 1011                5                3                2

Assuming that a higher value represents a higher educational level, I would like to create a new variable "Highest_degree_obtained" (below) that assigns a number based on the highest value contained within columns 2:4.

df$Highest_degree_obtained <- NA

Any suggestions on how to go about doing this?

M_Oxford
  • 361
  • 4
  • 11

1 Answers1

1

You could just use apply

df$Highest_degree_obtained <- apply(df[, -1], 1, function(x) {
  max(as.numeric(as.character(x)), na.rm = T)
})
df$Highest_degree_obtained
[1] 3 4 3 4 5 5 2 3 5 2 5
Sonny
  • 3,083
  • 1
  • 11
  • 19