An other basic question, but I can't seem to find a solution.
Take mtcars as an example. I would like to know the number of rows, where vs AND am are above 0.5. AND
df<- mtcars
x <- subset(mtcars, (vs > 0.5) & (am > 0.5))
OR
df<- mtcars
x <- subset(mtcars, (vs > 0.5) | (am > 0.5))
Easy so far.
Now I would like to vary exactly which column I want to use for filtering. And the column names I want are contained in an other dataframe. How can I do the filtering? How can I do it so that the column names are compared with OR or AND - that is all the column-row pairs are compared or either column-row pair.
df<- mtcars
colnames <- c("vs","am")
x <- subset(mtcars, mtcars[,colnames] > 0.5)
Does not give right answer... Thanks for help!
不是使用基本 R 的最聪明的解决方案,但我希望你理解方法:
mtcars[apply(mtcars[,colnames] > 0.5,1,function(x){ifelse(TRUE %in% x, TRUE, FALSE)}),]
An easier option is to use rowSums
sum(rowSums((mtcars[, colnames] > 0.5)) == 2)
and
sum(rowSums((mtcars[, colnames] > 0.5)) > 0)
An equivalent option can be done with lapply
and Reduce
lst1 <- lapply(mtcars[colnames], `>`, 0.5)
sum(Reduce(`&`, lst1))
sum(Reduce(`|`, lst1))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.