使用嵌套的ifelse复制VLOOKUP

时间:2017-03-29 09:54:28

标签: r nested

以下问题中“等于”的运算符是什么?

S1$CountryNo <- ifelse(S1$Country = 'UNITED KINGDOM' , 1 , ifelse(S1$Country = 'FRANCE' , 2 , 3)

1 个答案:

答案 0 :(得分:0)

如果您有很长的县列表,您还可以考虑查找向量:

S1 <- data.frame(CountryNo = c("UNITED KINGDOM", "FRANCE", "DENMARK"))

# Lookup vector
lookup <- c("UNITED KINGDOM" = 1, "FRANCE" = 2)

# Replace known countries - unknown (DENMARK) will be NA
S1$CountryNo <- lookup[S1$CountryNo]

# Replace NA countries with 3
S1[is.na(S1$CountryNo), "CountryNo"] <- 3