0

I'm trying to recode a variable based on two other variables and I think I'm misunderstanding how the ifelse statement works.

I have one column that is a string and then other is an integer. I want the new column to be the same as the string c1 unless the integer column flag equals 1, in which case it will equal XX.

  c1      flag    EXPECTED OUTPUT
  SS         0          SS
  SS         1          XX
  MM         0          MM
  LL         0          LL
  LL         0          LL
  SS         1          XX
  LL         0          LL      
  LL         1          XX
  SS         0          SS

I'm using ifelse as such:

df$expectedoutput <- ifelse(df$flag==1, "XX", df$c1)

I'm not sure if this is the best way to do a recode.

When I ask to view the new column I get this error:

Error in View : 'names' attribute [1849] must be the same length as the vector [1]
Yolo_chicken
  • 1,221
  • 2
  • 12
  • 24

1 Answers1

1

I believe you were bitten by stringsAsFactors=TRUE. This seems to give the expected output:

df <- read.table(text="
c1      flag
SS         0
SS         1
MM         0
LL         0
LL         0
SS         1
LL         0     
LL         1
SS         0", header=TRUE, stringsAsFactors=FALSE)

df$expected <- ifelse(df$flag == 1, "XX", df$c1)

> df
  c1 flag expected
1 SS    0       SS
2 SS    1       XX
3 MM    0       MM
4 LL    0       LL
5 LL    0       LL
6 SS    1       XX
7 LL    0       LL
8 LL    1       XX
9 SS    0       SS
Jason Morgan
  • 2,260
  • 21
  • 24