[英]Skip iteration and return NA in nested for loop in R
給定數據框:
test <- structure(list(IDcount = c(1, 1, 1, 1, 1, 2, 2, 2, 2, 2), year = c(1,
2, 3, 4, 5, 1, 2, 3, 4, 5), Otminus1 = c(-0.28, -0.28, -0.44,
-0.27, 0.23, -0.03, -0.06, -0.04, 0, 0.02), N.1 = c(NA, -0.1,
0.01, 0.1, -0.04, -0.04, -0.04, -0.04, -0.05, -0.05), N.2 = c(NA,
NA, -0.09, 0.11, 0.06, NA, -0.08, -0.08, -0.09, -0.09), N.3 = c(NA,
NA, NA, 0.01, 0.07, NA, NA, -0.12, -0.13, -0.13), N.4 = c(NA,
NA, NA, NA, -0.04, NA, NA, NA, -0.05, -0.05), N.5 = c(NA, NA,
NA, NA, NA, NA, NA, NA, NA, -0.13)), row.names = c(NA, -10L), groups = structure(list(
IDcount = c(1, 2), .rows = structure(list(1:5, 6:10), ptype = integer(0), class = c("vctrs_list_of",
"vctrs_vctr", "list"))), row.names = 1:2, class = c("tbl_df",
"tbl", "data.frame"), .drop = TRUE), class = c("grouped_df",
"tbl_df", "tbl", "data.frame"))
和結果數據框:
results <- structure(list(IDcount = c(1, 2), N.1 = c(NA, NA), N.2 = c(NA,
NA), N.3 = c(NA, NA), N.4 = c(NA, NA), N.5 = c(NA, NA)), row.names = c(NA,
-2L), class = "data.frame")
我想執行一個嵌套的 for 循環,如下所示:
index <- colnames(test) %>% str_which("N.")
betas <- matrix(nrow=length(unique(test$IDcount)), ncol=2)
colnames(betas) <- c("Intercept", "beta")
for (j in colnames(test)[index]) {
for (i in 1:2) {
betas[i,] <- coef(lm(Otminus1~., test[test$IDcount==i, c("Otminus1", j)]))
}
betas <- data.frame(betas)
results[[j]] <- betas$beta
}
for 循環應該在每一列和每個 ID 上運行回歸,並將系數寫入數據框“結果”。 這有效,只要每個 ID 在每一列中都有一個值。 不幸的是,我的數據框“test”在“N.5”列中缺少值。 因此無法執行回歸和循環,因為此 ID 的所有值都是 NA。
我現在想調整我的循環,以便僅當特定列中的某個 ID 至少有一個非 NA 值時才執行迭代。
按照這個解釋R for loop skip to next iteration ifelse ,我嘗試實現以下內容:
for (j in colnames(test)[index]) {
for (i in 1:2) {
if(sum(is.na(test[which(test[,1]==i),.]))==length(unique(test$year))) next
betas[i,] <- coef(lm(Otminus1~., test[test$IDcount==i, c("Otminus1", j)]))
}
betas <- data.frame(betas)
results[[j]] <- betas$beta
}
但這不起作用。
我想收到一個看起來像這樣的數據框“結果”:
IDcount N.1 N.2 N.3 N.4 N.5
1 0.1 0.2 0.5 0.3 NA
2 -5,3 -0.8 -0.4 -0.1 -0.1
任何幫助將不勝感激!!
您可以使用colSums
執行檢查:
index <- colnames(test) %>% str_which("N.")
betas <- matrix(nrow=length(unique(test$IDcount)), ncol=2)
colnames(betas) <- c("Intercept", "beta")
for (j in colnames(test)[index]) {
for (i in 1:2) {
tmp <- test[test$IDcount==i, c("Otminus1", j)]
if(any(colSums(!is.na(tmp)) == 0)) next
betas[i,] <- coef(lm(Otminus1~., tmp))
}
betas <- data.frame(betas)
results[[j]] <- betas$beta
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.