繁体   English   中英

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

[英]More efficient alternative for ifelse loop in R

为了基于另一个变量(类=因数)创建新变量,我进行了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"))))))

但是,我想知道是否有更有效的方法来做到这一点。 有什么建议么?

您可以执行以下操作:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM