cliftjc1
cliftjc1

Reputation: 63

Reversing variable values in R

I've seen various questions asked about recoding variables (e.g. Recoding variables with R) but I was wondering if there was an easy way to completely 'flip' the data. I'm currently working with a variable x that has a value from 0 to 30 that counts the number of days a patient did NOT spend in the ICU. What I want is the number of days spent in the ICU i.e. if someone didn't spend a single day in the ICU they'd have a value x=30 but I want a value x=0 and so and so forth. Obviously I could recode each value individually, but in the interest of saving key strokes and learning a little more about R, I was wondering if there was an easy solution.

Upvotes: 2

Views: 1884

Answers (4)

arcticfish48
arcticfish48

Reputation: 45

One minor addition to the function of Jeffrey Evans would be to specify the na.rm argument for max() and min()

inv <- function(x){ ((x - max(x, na.rm = TRUE)) * -1) + min(x, na.rm = TRUE) }

This way the function will also work in case of missing data.

Upvotes: 1

Jeffrey Evans
Jeffrey Evans

Reputation: 2397

You can just invert the data using (x - max(x)) * -1) + min(x)

inv <- function(x){ ((x - max(x)) * -1) + min(x) }
  icu <- 0:30
    inv(icu)

The reason for not simply subtracting is that this works on vectors with negative values as well.

( icu <- seq(-1,1,0.1) )
  inv(icu)

Upvotes: 4

user12256545
user12256545

Reputation: 3002

using subtraction:

x<-0:30
y<-30-x

Upvotes: 0

user438383
user438383

Reputation: 6206

Addition and subtraction in R are vectorised. This means you can apply a function to a vector and it will return a vector, rather than having to loop over the vector.

set.seed(999)
ICU = sample(30) ## number of days in ICU
not_ICU = 30 - ICU ## returns number of days not in ICU

Does that help?

Upvotes: 0

Related Questions