I am trying to recode a set of data that cannot be easily done with the split function or ifelse function. How would I recode the following data?
1 --> 1
2 --> 0
3 --> 0
4 --> 1
5 --> 1
7 --> 0
8 --> 1
Thank you for your time!
I am trying to recode a set of data that cannot be easily done with the split function or ifelse function. How would I recode the following data?
1 --> 1
2 --> 0
3 --> 0
4 --> 1
5 --> 1
7 --> 0
8 --> 1
Thank you for your time!
Another approach:
x <- +(x %in% c(1,4,5,8))
#[1] 1 0 0 1 1 0 1
The +(..)
nomenclature is a method to coerce a logical vector to integer the same way that as.integer(..)
would.
You could try:
library(car)
v <- c(1,2,3,4,5,6,7,8)
recode(v, "c(1,4,5,8) = 1; else = 0")
Or as per mentioned by @zx8754 you could use ifelse()
:
ifelse(v %in% c(1,4,5,8), 1, 0)
Which gives:
#[1] 1 0 0 1 1 0 0 1
Maybe try this? Although continuous-to-continuous usually implies some type of function that could be applied.
x <- c(1:5, 7:8)
x
# [1] 1 2 3 4 5 7 8
x[x == 1] <- 1
x[x == 2] <- 0
x[x == 3] <- 0
x[x == 4] <- 1
x[x == 5] <- 1
x[x == 7] <- 0
x[x == 8] <- 1
x
# [1] 1 0 0 1 1 0 1