0

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!

Tawk_Tomahawk
  • 139
  • 2
  • 8

3 Answers3

4

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.

Pierre L
  • 28,203
  • 6
  • 47
  • 69
  • 2
    `ifelse` is more general, but if OP really has a mapping into 0/1 output, this is the best approach. BTW `+` is the "R slang" for converting a logical into an integer parsimoniously. – MichaelChirico Oct 09 '15 at 17:52
  • I agree. There's no need for `ifelse` if this is the desired output. You wouldn't say `ifelse(condition, TRUE, FALSE)` since it is redundant. – Pierre L Oct 09 '15 at 17:53
2

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
Steven Beaupré
  • 21,343
  • 7
  • 57
  • 77
0

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
JasonAizkalns
  • 20,243
  • 8
  • 57
  • 116