我想基于一系列类似的变量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?谢谢!
答案 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))