Is there is function for subtraction calculation?

Wants to create a new variable by one variable minus another one, but don't know what function can be used. I know rowSums can be used to do addition, for example:
new variable value= Sleep + Dream

data(sleep) # use built-in data from package VIM
test<- sleep
test["NewVar"]<- rowSums(test[c(4,5)], na.rm=TRUE)

if wants to assign value by 5 minus 4 to new variable (NewVar=Sleep - Dream), how to do that? is there a specific function to do subtraction calculation? since data including missing value, have to use function with a option na.rm=T.

I understand that your looking for the minus equivalent of the sum that can handle NA values.
As far as I know there is no such standard ('builtin') function but you can make your own:

minus <- function(x) sum(x[1],na.rm=T) - sum(x[2],na.rm=T)

You can use this function on a pair of numbers :

> x=c(4,NA) ; minus(x) 
[1] 4

and with the apply function on a data.frame e.g.

> df = data.frame(x=c(1,1,NA,NA),y=c(1,NA,1,NA)) 
> df
   x  y
1  1  1
2  1 NA
3 NA  1
> apply(df[,c(1,2)],1,minus) # use columns 1 and 2 of df
[1]  0  1 -1  0
> apply(df[,c('x','y')],1,minus)  # use columns x and y of df
[1]  0  1 -1  0

So in your case this could (I do not have the VIM package installed!) work :

NewVar = apply(test[,c('Sleep','Dream')],1,minus)

1 Like

Pretty cool! works very well, modified a little bit, can also be used for multiply and divide calculation. Thank you!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.