Reputation: 35
So I want to create a function that takes a numeric vector as an argument, and takes the max value and the min value and calculates the difference between. I've got to this point so far:
v <- as.numeric()
minmax <- function(v){max(v)-min(v)}
minmax (v)
The function works, but I'm sure there is a more convenient way to write this in R
I want to add a 2nd argument, called noNAs which defines how the function handles its vectors missing values (NAs) and i would like to have it so when noNAs=TRUE it calculates the difference between max and min without including the NA values. I know there is a way to implement this with na.rm but i have no idea how. I was thinking like this, but it doesn't seem to work:
minmax <- function(v,noNAs=T){max(v)-min(v){na.rm=TRUE}}
Upvotes: 0
Views: 2898
Reputation: 17279
You've very nearly solved your own problem by recognizing that na.rm
is an argument that controls how missing values are treated. Now you just need to apply this knowledge to both min
and max
.
The benefit of functions is that you can pass your arguments to other functions, just as you have passed v
. The following will define what you wish:
minmax <- function(v, noNA = TRUE){
max(v, na.rm = noNA) - min(v, na.rm = noNA)
}
I would recommend, however, that you use an argument name that is familiar
minmax <- function(v, na.rm = TRUE){
max(v, na.rm = na.rm) - min(v, na.rm = na.rm)
}
As pointed out earlier, you may be able to simplify your code slightly by using
minmax <- function(v, na.rm = TRUE){
diff(range(v, na.rm = na.rm))
}
Lastly, I would suggest that you don't use T
in place of TRUE
. T
is a variable that can be reassigned, so it isn't always guaranteed to be TRUE
. TRUE
, on the other hand, is a reserved word, and cannot be reassigned. Thus, it is a safer logical value to use.
Upvotes: 2