R中ifelse循环的更有效替代方案

时间:2014-05-06 20:02:47

标签: r if-statement

为了根据另一个变量(class = factor)创建一个新变量,我做了一个ifelse循环。

数据:

eu <- data.frame(structure(c(1L, 4L, 5L, 12L, 9L, 13L, 16L, 18L, 27L, 10L, 25L, 21L, 28L, 19L, 8L, 26L, 6L, 3L, 15L, 14L, 11L, 17L, 20L, 23L, 24L, 2L, 22L, 7L), .Label = c("Belgie", "Bulgarije", "Cyprus", "Denemarken", "Duitsland", "Estland", "Europese Unie", "Finland", "Frankrijk", "Griekenland", "Hongarije", "Ierland", "Italie", "Letland", "Litouwen", "Luxemburg", "Malta", "Nederland", "Oostenrijk", "Polen", "Portugal", "Roemenie", "Slovenie", "Slowakije", "Spanje", "Tsjechie", "Verenigd Koninkrijk", "Zweden"), class = "factor"))
names(eu) <- "land"

我的ifelse循环:

eu$plicht <- ifelse(eu$land=="Belgie", "ja",
                    ifelse(eu$land=="Italie","ja",
                           ifelse(eu$land=="Cyprus","ja",
                                  ifelse(eu$land=="Griekenland","ja",
                                         ifelse(eu$land=="Luxemburg","ja",
                                                ifelse(eu$land=="Spanje","ja","nee"))))))

但是,我想知道是否有更有效的方法。有什么建议吗?

1 个答案:

答案 0 :(得分:2)

您可以执行以下操作:

eu$plicht <- ifelse(eu$land %in% c("Belgie", "Italie", "Cyprus", "Griekenland", "Luxemburg", "Spanje"),
                    "ja", "nee")
相关问题