簡體   English   中英

R-根據向量中的任何值編寫條件語句

[英]R - Write conditional statement based on any value in a vector

我正在嘗試編寫條件語句,該條件語句將檢查向量中的任何值是否滿足條件,然后根據該條件寫入結果。 在下面的示例中,我知道c2的總和比其他列小得多,但是在我的實際數據中,我不知道哪一列的總和較小。 我想檢查csums向量中的任何值是否小於.1,如果是,則將列索引寫入數據幀。 此外,在某些情況下,.1下面會有兩列,因此我需要將兩個列索引都寫入數據幀。

c1 <- runif(16,.3,.6)
c2 <- c(.01,.01,.01,.01,rep(.00,12))
c3 <- runif(16,.3,.6)
c4 <- runif(16,.3,.6)
c5 <- runif(16,.3,.6)
test.mat1 <- cbind(c1,c2,c3,c4,c5)
csums1 <- colSums(test.mat1)
csums1
      c1       c2       c3       c4       c5 
7.279773 0.040000 6.986803 7.200409 6.867637

c6 <- runif(16,.3,.6)
c7 <- runif(16,.3,.6)
c8 <- c(.01,.01,.01,.01,rep(.00,12))
c9 <- c(.01,.01,.01,.01,rep(.00,12))
c10 <- runif(16,.3,.6)
test.mat2 <- cbind(c6,c7,c8,c9,c10)
csums2 <- colSums(test.mat2)
csums2
      c6       c7       c8       c9      c10 
7.198180 7.449324 0.040000 0.040000 8.172110 

結果樣本如下所示:

result <- matrix(c(2,0,3,4),nrow=2,byrow=T)
result
     [,1] [,2]
[1,]    2    0
[2,]    3    4

其中,第1行記錄了第2列的總和小於.1,而第2行記錄了列表中下一個數據幀中的第3列和第4列的總和小於1.。 我的實際數據是一個列表,其中包含數千個數據幀,結果數據幀繼續顯示整個列表。 我計划將此條件語句嵌入循環中以遍歷每個列表元素。

這是一個解決方案,將您提供的矩陣test.mat1test.mat2的列表作為輸入:

my_list <- list(test.mat1, test.mat2)

# For each data frame in the list, compute the column sums
# and return the indices of the columns for which the sum < 0.1
res <- lapply(my_list, function(x) {
  which(colSums(x) < 0.1)
})

# Get the number of columns for each element of the list
len <- lengths(res)
if(any(len == 0)) { # in case you have no values < 0.1, put a 0
  res[which(len == 0)] <- 0
}

# Get your result:
result <- do.call("rbind", res)

# replace duplicated values by 0:
result[t(apply(result, 1, duplicated))] <- 0

示例數據:

set.seed(1234)
df1 <- data.frame(
    c1 = runif(16,.3,.6),
    c2 = c(.01,.01,.01,.01,rep(.00,12)),
    c3 = runif(16,.3,.6),
    c4 = runif(16,.3,.6),
    c5 = runif(16,.3,.6)
)

df2 <- data.frame(
    c6  = runif(16,.3,.6),
    c7  = runif(16,.3,.6),
    c8  = c(.01,.01,.01,.01,rep(.00,12)),
    c9  = c(.01,.01,.01,.01,rep(.00,12)),
    c10 = runif(16,.3,.6)
)

創建要使用的數據框名稱的向量

vec_of_df_names <- c("df1", "df2")

遍歷數據幀:

res_mat <- matrix(0, nrow=2, ncol=5)
for(i in seq_along(vec_of_df_names)) {
    res <- which(colSums(get(vec_of_df_names[i])) < 0.1)
    if(length(res)>0) res_mat[i, seq_along(res)] <- res
}
res_mat

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM