20

I have read many of the if statement posts but have not been able to find an answer to my simple problem. I would like to create a new column in the data frame 'tester' based on a multiple condition if statement.

tester<- as.data.frame(matrix(data=c(seq(1,300,by=1.5)), ncol=4))

if (tester$V3> 200 && tester$V4>250){tester[,5] <- "one"} else tester$V5 <-NA

This gives me NAs for the entire column even though the last 17 rows are TRUE for both cases and should be "one". What is happening here? Thank you for your help!

user3431218
  • 201
  • 1
  • 2
  • 5
  • 11
    tester$V5 <- ifelse (tester$V3> 200 & tester$V4>250,"one",NA) – HubertL Sep 19 '16 at 21:02
  • thank you that works! why did mine not work? – user3431218 Sep 19 '16 at 21:18
  • 1
    Because you used && – Hack-R Sep 19 '16 at 21:32
  • Rewrite like this to make it work `if (i <- (tester$V3> 200 & tester$V4>250)) {tester$V5[i] <- "one"} else {tester$V5[i] <-NA}` – Vlo Sep 19 '16 at 21:35
  • @Vlo No this doesn't work (Try it with `tester <- data.frame(V3=c(1,220,3), V4=c(5,600,7))`) because the first value of the condition is used for the test and is `false`. This would work `if (i <- (tester$V3> 200 & tester$V4>250)) {tester$V5[i] <- "one"} else {tester$V5[i] <-"one"}` but is so ugly!!! – HubertL Sep 19 '16 at 22:37
  • @HubertL Forgot to wrap `any` around the condition. Your code is the exact the same thing with a hypo instead. `if (any(i <- (tester$V3> 200 & tester$V4>250))) {tester$V5[i] <- "one"} else {tester$V5[i] <-NA}` – Vlo Sep 20 '16 at 20:07
  • @Vlo there is no real reason to use a if then, it's clearer to write the statement in 2 lines : `i <- tester$V3> 200 & tester$V4>250` and `tester$V5[i] <- "one"` – HubertL Sep 20 '16 at 20:35

1 Answers1

15

Read this thread R - boolean operators && and ||.

Basically, the & is vectorized, i.e. it acts on each element of the comparison returning a logical array with the same dimension as the input. && is not, returning a single logical.

Community
  • 1
  • 1
catastrophic-failure
  • 3,759
  • 1
  • 24
  • 43