[英]Why can't I assign a value to a vector as the result of a conditional statement in 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.mat1
和test.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.