将循环结果附加到向量

时间:2019-11-07 00:59:27

标签: r

我正在尝试获取值“ 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'

2 个答案:

答案 0 :(得分:1)

我们可以使用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
   }
}

答案 1 :(得分:1)

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