gpt4 book ai didi

r - 将循环结果附加到向量

转载 作者:行者123 更新时间:2023-12-04 11:02:07 25 4
gpt4 key购买 nike

我正在尝试获取值“a”的计数大于或等于 2 的变量名称列表,并最终将其存储在向量 Morethan2 中,同样对 lessthan2 执行同样的操作。请帮助我实现这一目标。

df <- data.frame(a1 = c("a","a","b"),a2 = c("a","b","b"),a3 = c("a","a","a"))
for(x in names(df[1:3])){
if(sum(df[x] =="a") >= 2){
more2 = x
} else{less2 = x}}
Lessthan2 = less2
Morethan2 = more2


预期结果:
Morethan2  : 'a1','a3'
Lessthan2 : 'a2'

最佳答案

我们可以使用 colSums获取 "a" 的计数在每一列中,然后对其进行子集化以获得 morethan2lessthan2 .

inds <- colSums(df == "a")
morethan2 <- names(inds)[inds >= 2]
lessthan2 <- names(inds)[inds < 2]

morethan2
#[1] "a1" "a3"
lessthan2
#[1] "a2"

如果我们想使用 for循环,我们可以做
i <- 1
j <- 1
more2 <- numeric()
less2 <- numeric()

for(x in names(df)) {
if(sum(df[[x]] =="a") >= 2) {
more2[i] = x
i= i + 1
} else {
less2[j] = x
j = j + 1
}
}

关于r - 将循环结果附加到向量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58740513/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com