R 中分类变量的高效通用重新编码
Efficient and generic recoding of categorical variables in R
想象一下这样的 data.table
library(data.table)
DT = data.table(values=c('call', NA, 'letter', 'call', 'e-mail', 'phone'))
print(DT)
values
1: call
2: <NA>
3: letter
4: call
5: e-mail
6: phone
我希望通过以下映射重新编码值
mappings = list(
'by_phone' = c('call', 'phone'),
'by_web' = c('e-mail', 'web-meeting')
)
即我想将 call
转换为 by_phone
等。NA
应该放在 missing
中,未知(通过提供的映射)放在 other
中。对于这个特定的数据 table 我可以通过以下方式简单地解决我的问题
recode_group <- function(values, mappings){
ifelse(values %in% unlist(mappings[1]), names(mappings)[1],
ifelse(values %in% unlist(mappings[2]), names(mappings)[2],
ifelse(is.na(values), 'missing', 'other')
)
)
}
DT[, recoded_group:=recode_group(values, mappings)]
print(DT)
values recoded_group
1: call by_phone
2: <NA> missing
3: letter other
4: call by_phone
5: e-mail by_web
6: phone by_phone
但我正在寻找一种高效且通用的 recode_group
功能。有什么建议吗?
这是一个更新加入方法的选项:
DT[stack(mappings), on = "values", recoded_group := ind]
DT[is.na(values), recoded_group := "missing"]
DT
# values recoded_group
#1: call by_phone
#2: NA missing
#3: letter NA
#4: call by_phone
#5: e-mail by_web
#6: phone by_phone
想象一下这样的 data.table
library(data.table)
DT = data.table(values=c('call', NA, 'letter', 'call', 'e-mail', 'phone'))
print(DT)
values
1: call
2: <NA>
3: letter
4: call
5: e-mail
6: phone
我希望通过以下映射重新编码值
mappings = list(
'by_phone' = c('call', 'phone'),
'by_web' = c('e-mail', 'web-meeting')
)
即我想将 call
转换为 by_phone
等。NA
应该放在 missing
中,未知(通过提供的映射)放在 other
中。对于这个特定的数据 table 我可以通过以下方式简单地解决我的问题
recode_group <- function(values, mappings){
ifelse(values %in% unlist(mappings[1]), names(mappings)[1],
ifelse(values %in% unlist(mappings[2]), names(mappings)[2],
ifelse(is.na(values), 'missing', 'other')
)
)
}
DT[, recoded_group:=recode_group(values, mappings)]
print(DT)
values recoded_group
1: call by_phone
2: <NA> missing
3: letter other
4: call by_phone
5: e-mail by_web
6: phone by_phone
但我正在寻找一种高效且通用的 recode_group
功能。有什么建议吗?
这是一个更新加入方法的选项:
DT[stack(mappings), on = "values", recoded_group := ind]
DT[is.na(values), recoded_group := "missing"]
DT
# values recoded_group
#1: call by_phone
#2: NA missing
#3: letter NA
#4: call by_phone
#5: e-mail by_web
#6: phone by_phone