搜索 'education' 个变量范围并根据这些变量中包含的最高资格分配一个数字

Search through range of 'education' variables and assign a number based on the highest qualification contained within these variables

我目前是一名 R 新手,在我的数据集中重新编码变量时遇到了一个问题。如果您对这个问题有任何建议,我将不胜感激。我有几个不同的 "education_code" 变量,其中包含有关给定个人教育资格的信息。

#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'))

看起来像这样:

     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

假设较高的值代表较高的教育水平,我想创建一个新变量 "Highest_degree_obtained"(下图),它根据列 2:4 中包含的最高值分配一个数字。

df$Highest_degree_obtained <- NA

关于如何进行此操作的任何建议?

你可以直接使用 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