如果是在R中的循环中

时间:2018-05-22 19:26:02

标签: r loops if-statement

我想基于一系列类似的变量zipid1到zipid26创建一个变量区域。我目前的代码是这样的:

dat$region <- with(dat, ifelse(zipid1 == 1, 1, 
                                         ifelse(zipid2 == 1, 2, 
                                                ifelse(zipid3 == 1, 3,
                                                       ifelse(zipid4 == 1, 4,
                                                              5)))))

如何编写循环以避免从zipid1输入到zipid26?谢谢!

1 个答案:

答案 0 :(得分:0)

我们对'zipid'列进行子集,通过与1(== 1)进行比较来创建逻辑矩阵,获取TRUE值与max.col的列索引(假设只有{每行一个,并指定它来创建'region'

dat$region <- max.col(dat[paste0("zipid", 1:26)] == 1, "first")

使用一个可重复的小例子

max.col(dat[paste0("zipid", 1:5)] == 1, "first")

数据

dat <- data.frame(id = 1:5, zipid1 = c(1, 3, 2, 4, 5), 
  zipid2 = c(2, 1, 3, 5, 4), zipid3 = c(3, 2, 1, 5, 4),
  zipid4 = c(4, 3, 6, 2, 1), zipid5 = c(5, 3, 8, 1, 4))