-1

I have a sample dataset below:

Col1    Col2    Col3
   A       6       9  
   B       7      10
   C       8      11
   C       9      12
   D      10      13

How do I do an ifelse statement that says - "If Col1 does not have the values A and B, then make Col3 = Col2, if not, keep original values."

Final expected output:

Col1    Col2    Col3
   A       6       9  
   B       7      10
   C       8       8
   C       9       9
   D      10      10

This was my attempt but it didn't work:

df$Col3 <- ifelse(df$Col1!="A" & df$Col1!="B", df$Col2, df$Col3)
nak5120
  • 4,089
  • 4
  • 35
  • 94

2 Answers2

2
library(dplyr)    
df %>%
  mutate(Col3 = ifelse(Col1 %in% c("A","B"),Col3,Col2))
Eric
  • 1,381
  • 9
  • 24
0

Here is the true answer to your question:

Why can't R's ifelse statements return vectors?

As for code which will work, case_when is a much more useful implementation

library(dplyr)

df %>%
  mutate(Col3 = case_when(
    Col1 %in% c("A","B") ~ Col3,
    TRUE ~ Col2
    )
  )
glaucon
  • 238
  • 3
  • 10
  • This is completely unrelated to your linked question. – Matthew Lundberg Jan 09 '19 at 23:16
  • Did you read this? “So ifelse is intended for the specific purpose of testing a vector of booleans and returning a vector of the same length, filled with elements taken from the (vector) yes and no arguments.” – glaucon Jan 09 '19 at 23:48
  • His vector is the same length as the intended result. Yes, I read both questions. Note that the comment above says nothing about the solution you have provided. Just that the linked question is about something else entirely. – Matthew Lundberg Jan 09 '19 at 23:54
  • Reviewing the initial input, I was unable to produce an error at all (lol). That fact alone renders both my link & the solution useless! It is certainly unrelated as a result. Cheers – glaucon Jan 10 '19 at 00:13