2

I am trying to get the list of variable names where the count of value "a" is more than or equals 2 and finally store it in a vector Morethan2 and similarly do for the lessthan2. Please help me to achieve this.

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 

Expected REsult:

Morethan2 : 'a1','a3' Lessthan2 : 'a2' 

2 Answers 2

1

We can use colSums to get the count of "a" in each column and then subset it to get morethan2 and lessthan2.

inds <- colSums(df == "a") morethan2 <- names(inds)[inds >= 2] lessthan2 <- names(inds)[inds < 2] morethan2 #[1] "a1" "a3" lessthan2 #[1] "a2" 

If we want to use for loop, we can do

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 } } 
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Ronak, could you also please post the same using the for loop?
@prog Updated the answer.
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}} 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.