I wrote a R function to return rows satisfying specific requirements, but I got problem with output format.
For example, return rows with certain values:
xx.1 <- data.frame(aa= 1:5, bb = c("AA","BB","CC","DD","EE"))
xx.2 <- c("AA","DD")
ff_in <- function(x,y){
if (toupper(x[2]) %in% y) {return(x)}
}
apply(xx.1,1,ff_in,xx.2)
However, the output looks like :
[[1]]
aa bb
"1" "AA"
[[2]]
NULL
[[3]]
NULL
[[4]]
aa bb
"4" "DD"
[[5]]
NULL
How to suppress R return null, and return something likes this?
aa bb
"1" "AA"
"4" "DD"
How about
do.call(rbind,apply(xx.1,1,ff_in,xx.2))
? That combines all the results row-by-row; rbind
ing a NULL
vector has no effect.
Wouldn't it be easier to just do:
xx.1[ toupper(xx.1[[2]]) %in% xx.2 , ]
If you needed it in a function, I'm sure this would be faster and would also not have the undesirable side-effect of coercion of a dataframe to a character matrix.
exncol <- function(df, coln, choices) df[ toupper(df[[coln]]) %in% choices , ]
exncol(xx.1, 2, xx.2)
aa bb
1 1 AA
4 4 DD
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With