0

i have this kind of data

t1 <- data.frame(c1=c(1,2,5,NA,3,2),c2=c(1,3,NA,NA,8,3),c3=c(NA,8,7,NA,8,4))

> t1
  c1 c2 c3
  1  1  1 NA
  2  2  3  8
  3  5 NA  7
  4 NA NA NA
  5  3  8  8
  6  2  3  4

is it possible to shorten this kind of expression?

ifelse(t1["c1"] == 1 | t1["c1"] == 2 | t1["c1"] == 3, "yes", "no")

something like this doesnt work:

ifelse(t1["c1"] %in% c(1,2,3), "yes", "no")
elajdsha
  • 95
  • 7

2 Answers2

1

All you need is to use the [[ operator to extract the vector:

t1[["c1"]] %in% c(1,2,3)

ifelse(t1[["c1"]] %in% c(1,2,3), "yes", "no")
#[1] "yes" "yes" "no"  "no"  "yes" "yes"

Yours doesn't work because you are trying to use the %in% operator on a data.frame column.

Note the difference:

t1["c1"] 
#  c1
#1  1
#2  2
#3  5
#4 NA
#5  3
#6  2

t1[["c1"]] 
#[1]  1  2  5 NA  3  2
Ian Campbell
  • 23,484
  • 14
  • 36
  • 57
0

You of course can try:

t1$New <- ifelse(t1$c1 %in% c(1,2,3), "yes", "no")

  c1 c2 c3 New
1  1  1 NA yes
2  2  3  8 yes
3  5 NA  7  no
4 NA NA NA  no
5  3  8  8 yes
6  2  3  4 yes
Duck
  • 39,058
  • 13
  • 42
  • 84