如何使用(data.frame)查找表中的值标签替换数据框中的数字代码?

Eri*_*ail 4 replace r rename variable-assignment dataframe

这是这个问题的后续问题,最初受到这个问题的启发,但并不完全相同.

这是我的情况.首先我从数据库中提取一些数据,

df <- data.frame(id = c(1:6),
                 profession = c(1, 5, 4, NA, 0, 5))
   df
#  id profession
#  1          1
#  2          5
#  3          4
#  4         NA
#  5          0
#  6          5
Run Code Online (Sandbox Code Playgroud)

其次,我提供了一个关键字表,其中包含有关行业代码的人类可读信息,

profession.codes <- data.frame(profession.code = c(1,2,3,4,5),
                               profession.label = c('Optometrists',
                               'Accountants', 'Veterinarians', 
                               'Financial analysts',  'Nurses'))                 
   profession.codes
#  profession.code   profession.label
#               1       Optometrists
#               2        Accountants
#               3      Veterinarians
#               4 Financial analysts
#               5             Nurses
Run Code Online (Sandbox Code Playgroud)

现在,我想profession用我df的标签来覆盖我的变量profession.codes,最好是joinplyr包中使用,但我对任何智能解决方案都持开放态度.虽然我喜欢那个ply保留x的顺序.

我现在这样做,

# install.packages('plyr', dependencies = TRUE)
library(plyr)

profession.codes$profession <- profession.codes$profession.code
df <- join(df, profession.codes, by="profession")
# levels(df$profession.label)
df$profession.label <- factor(df$profession.label, 
   levels = c(levels(df$profession.label), 
   setdiff(df$profession, df$profession.code)))
# levels(df$profession.label)
df$profession.label[df$profession==0 ] <- 0
df$profession.code <- NULL
df$profession  <- NULL
names(df) <- c("id", "profession")
df
#  id         profession
#  1       Optometrists
#  2             Nurses
#  3 Financial analysts
#  4               <NA>
#  5                  0
#  6             Nurses
Run Code Online (Sandbox Code Playgroud)

这就是我如何覆盖profession而不失去NA0.

问题是0可能是17或任何数字,我想以某种方式解释这个问题.此外,如果可能的话,我还想缩短我的代码.

任何帮助将不胜感激.

谢谢,埃里克

Tyl*_*ker 6

这是基础中的一种方法:

df <- data.frame(id = c(1:6),
                 profession = c(1, 5, 4, NA, 0, 5))

pc <- data.frame(profession.code = c(1,2,3,4,5),
                               profession.label = c('Optometrists',
                               'Accountants', 'Veterinarians', 
                               'Financial analysts',  'Nurses'))  


df$new <- as.character(pc[match(df$profession,  
    pc$profession.code), 'profession.label'])
df[is.na(df$new), 'new'] <- df[is.na(df$new), 'profession'] 
df$new <- as.factor(df$new)
df
Run Code Online (Sandbox Code Playgroud)

产量:

  id profession                new
1  1          1       Optometrists
2  2          5             Nurses
3  3          4 Financial analysts
4  4         NA               <NA>
5  5          0                  0
6  6          5             Nurses
Run Code Online (Sandbox Code Playgroud)

  • 我没有覆盖你建议的列,因为当你可以创建一个新列时,我不喜欢覆盖某些东西.如果要覆盖原始列,请更改我的解决方案以执行此操作. (2认同)