id=1:5
age1=c(67,39,97,55,37)
age2=c(300,122,333,70,333)
age3=c(1,3,6,1,3)
age4=c(56,33,34,77,99)
gender=c("f","m","f","f","m")
data=data.frame(id, age1, age2, age3, age4, gender)
length(data$age1[data$age1 > 50])/length(data$age1)
length(data$age2[data$age2 > 50])/length(data$age2)
length(data$age3[data$age3 > 50])/length(data$age3)
length(data$age4[data$age4 > 50])/length(data$age4)
First, I want to grab the age columns (age1, age2, age3, age4) using %in% operator (grab the columns whose name has age in it)
and then, I want to calculate the proportion- but my code seems to be inefficient. This is a reproducible example, and in my data, I have different 30 ages...
A
basesolution withgrep()to extract column names containing"age":You can also use
summarise()withacross()fromdplyr.Hint: You can use
mean()to get the proportion ofTRUEof a logical vector.