r - #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}
}
不知道为什么这不起作用...
解决方案
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?
}
推荐阅读
- spring-data-jpa - 如何在 Spring Data jpa 中获取 Connection 对象?
- java - Javafx:添加图像:java.lang.reflect.InvocationTargetException
- c++ - CodeLite 中的调试器未显示局部变量
- python - 修复图像中曝光过度的区域
- python-3.x - 合并具有重复名称的多索引列
- python - z:net.snowflake.spark.snowflake.Utils.runQuery。: java.lang.NullPointerException
- reactjs - 泛型还是分解?什么是正确的反应方法
- java - 如何在 Spring Boot 中从数据库更新应用程序上下文
- ios - 有没有一种简单的方法可以从 UITableView 中删除特定的自定义单元格?
- javascript - 转到路线并在事件处理程序中传递道具