3 回答
TA贡献1804条经验 获得超8个赞
# some sample dataidnat <- sample(c("french","foreigner"),100,TRUE)idbp <- rep(NA,100)idbp[idnat=="french"] <- sample(c("mainland","overseas","colony"),sum(idnat=="french"),TRUE)# recodingout <- ifelse(idnat=="french" & !idbp %in% c("overseas","colony"), "mainland", ifelse(idbp %in% c("overseas","colony"),"overseas", "foreigner"))cbind(idnat,idbp,out) # check result
if
else
if("french"=="french")
if(c("french","foreigner")=="french")
ifelse
if
else
ifelse
TA贡献1876条经验 获得超5个赞
如果数据集包含许多行,则使用data.table而不是嵌套ifelse().
提供了下面的查找表
lookup
idnat idbp idnat2
1: french mainland mainland
2: french colony overseas
3: french overseas overseas
4: foreign foreign foreign
和一个样本数据集
library(data.table)
n_row <- 10L
set.seed(1L)
DT <- data.table(idnat = "french",
idbp = sample(c("mainland", "colony", "overseas", "foreign"), n_row, replace = TRUE))
DT[idbp == "foreign", idnat := "foreign"][]
idnat idbp
1: french colony
2: french colony
3: french overseas
4: foreign foreign
5: french mainland
6: foreign foreign
7: foreign foreign
8: french overseas
9: french overseas
10: french mainland
然后我们可以做一个加入时更新:
DT[lookup, on = .(idnat, idbp), idnat2 := i.idnat2][]
idnat idbp idnat2
1: french colony overseas
2: french colony overseas
3: french overseas overseas
4: foreign foreign foreign
5: french mainland mainland
6: foreign foreign foreign
7: foreign foreign foreign
8: french overseas overseas
9: french overseas overseas
10: french mainland mainland
- 3 回答
- 0 关注
- 533 浏览
添加回答
举报