【发布时间】:2016-12-02 02:39:55
【问题描述】:
我有一个循环,它重新编码列的值并在满足条件时中断。我想在具有相同格式的数据框列表上使用此循环或其基本概念。
样本数据:
Id <- as.factor(c(rep("01001", 11), rep("01043", 11), rep("01065", 11), rep("01069", 11)))
YearCode <- as.numeric(rep(1:11, 4))
Type <- c(NA,NA,NA,NA,NA,NA,NA,2,NA,NA,NA,NA,NA,NA,
NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,
NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,2,NA)
test <- NA
sample_df <- data.frame(Id, YearCode, Type, test)
# A part of sample_df
one_df <- subset(sample_df, sample_df$Id=="01069")
这个 for 循环适用于一个数据帧:
# example for loop using example data frame "one_df"
for(i in seq(along=one_df$Id)){
if(is.na(one_df$Type[i])){ # if Type is NA, recode to 0
one_df$test[i] <- 0
} else { # Stop when Type is not NA, and leave remaining NAs that come after
break }
}
但是,我在列表中有许多具有相同格式的数据框。我想将它们保留在列表中,并将此循环应用于整个列表。
# example list : split data frame into list by Id
sample_list <- split(sample_df, sample_df$Id, drop = TRUE)
我查看了其他帖子,例如 this one,但在尝试遍历列表中的每个数据帧或使用 lapply 编写类似的函数时,我遇到了困难。如何使用 for 循环、lapply 或其他方式修改此循环以在列表 (sample_list) 上工作?
任何提示将不胜感激,如果我需要澄清任何事情,请告诉我。谢谢!
【问题讨论】: