Z_D
Z_D

Reputation: 817

Adding na.rm to Custom R Function with sapply

I am struggling to add an na.rm command to a custom function (just a percentage) seen below on a dataframe where each column is a point in time filled with prices of the securities that are identified in the rows. This df contains quite a bit of NAs. Here is the function:

pctabovepx=function(x) {
  count_above_px=x>pxcutoff
  100*(sum(count_above_px)/nrow(count_above_px))
}

I then want to run this function withinan sapply on all columns of my df with price data, as specified in the range below. Without adding an na command, it returns nothing ("numeric(0)") but when I add an na.rm command as I would with a function like mean, it returns "Error in FUN(X[[1L]], ...) : unused argument (na.rm = TRUE)".

abovepar=sapply(master[min_range:max_range], pctabovepx)
abovepar=sapply(master[min_range:max_range], pctabovepx, na.rm=TRUE)

I also tried to simplify and just do a count before doing a percentage. The following command did not return an error but just returned all values that were not NA, instead of the subset with prices above the cutoff.

countsabovepx=as.data.frame(sapply(master[min_range:max_range],function(x) sum(!is.na(x>pxcutoff))))

I am wondering how to avoid this issue, both with this function and generally with self-written functions that aren't mean or median.

Upvotes: 0

Views: 4100

Answers (1)

James
James

Reputation: 66834

You need to add it to your function as an argument and pass it to the sum. You also need to take account of the effect on the nrow part too. However, in the context of the rest of the function, I expect count_above_px to be a vector and nrow not to make sense here. I presume you meant to do length, and you are actually computing the mean, which has the na.rm argument anyway. You might also want to look at pxcutoff as it is not defined in the function - should this be passed as an argument too?

pctabovepx=function(x, na.rm=FALSE) {
  count_above_px=x>pxcutoff
  100*mean(count_above_px, na.rm=na.rm)
}

Upvotes: 6

Related Questions