想象一下这样的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
。对于这个特定的数据表,我可以通过以下
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
功能。有什么建议吗?
答案 0 :(得分:1)
这是一个采用更新加入方式的选项:
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