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,第二行记录列表中下一个数据框中的第 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