Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to suppress the function to return "Null" in R?

Tags:

return

r

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" 
like image 304
ccshao Avatar asked Dec 21 '22 23:12

ccshao


2 Answers

How about

do.call(rbind,apply(xx.1,1,ff_in,xx.2))

? That combines all the results row-by-row; rbinding a NULL vector has no effect.

like image 83
Ben Bolker Avatar answered Dec 24 '22 02:12

Ben Bolker


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
like image 38
IRTFM Avatar answered Dec 24 '22 00:12

IRTFM