首页 > 解决方案 > #R - FOR 循环 - 如何遍历 data.frame 列中向量的每个元素

问题描述

目标是创建一个向量,指示学生是否缺席(1)、在场(0)或数据是否丢失(NA)

Present <- data$attendancecode
attendance <- c()

for (i in seq_along(Present)){
  if (is.na(i)==TRUE) {
    attendance [i] <- NA
  } else if (grepl("A|G|X|Z", i)){
    attendance [i] <- 1
  } else {attendance [i] <- 0}
}

不知道为什么这不起作用...

标签: rfor-loop

解决方案


seq_along会给你一个索引向量,即1:length(Present). 所以你的is.na电话总是会返回假的。而是做

for (i in seq_along(Present)){
  if (is.na(present[i])) { # don't need == TRUE, is.na returns TRUE or FALSE
    attendance [i] <- NA
  } else if (grepl("A|G|X|Z", i)){
    attendance [i] <- 1
  } else {Present [i] <- 0} # not sure what you intend to do here... do you mean to overwrite the value in Present? or do you mean to assign to attendance?
}

推荐阅读