1
votes

I have the following sample data:

A = data.frame( x=c('x','x','y','y','z','z'), j=c(1,1,1,2,2,3)   )
A$z[A$x=="x"]=1
A$z[A$x=="y"]=1
A$z[is.na(A$z)]=0

And I would like to create a new column "Test" using column "z" equal to 1 as condition and take value of column "x".

I use the following statement but there is a warning message

if(A$z==1)A$Test=A$z

Warning message: In if (A$z == 1) A$Test = A$z : the condition has length > 1 and only the first element will be used

How can I correct this?

2
I am the following sample data - nice to meet you, A ;-) - talat
A[ "Test" ] <- ifelse( A$z == 1, A$x, 9 ) - vaettchen
Thanks @ vaettchen, but the column return number instead of the exact value of column "x" - Raphael Li
idx <- A$z == 1; A$Test[idx] <- as.character(A$x[idx])? - talat
This is because your column x is a factor. For the sample data you can get around this with A[ "Test" ] <- ifelse( A$z == 1, as.character( A$x ), 9 ). for your real data, check with str( A ) what data type you have. - vaettchen

2 Answers

3
votes

We can also do

A$Test <- NA^(A$z!=1)*A$z
1
votes

Create the test variable as part of the data frame and use ifelse() to add the appropriate values. Consider:

A$Test = ifelse(A$z==1, A$z, NA)