Reputation: 109
I got the data frame
Z1 Z2 Z3 Z4
AB XX 1 100
BA YY 2 200
AB YY 1 200
BA XX 2 100
And I want to make a new column picking Z1 or Z2 depending on the values in Z3 and Z4.
The conditions are if Z3= h1 or Z4=h10 then Z5 is Z1 else Z5=Z1; the table should look like this:
Z1 Z2 Z3 Z4 Z5
AB XX h1 h10 AB
BA YY h2 h20 YY
AB YY h1 h20 AB
BA XX h2 h10 BA
To achieve this I do:
df = within(df,{
Z5 == ifelse(df$Z3 == "h1" | df$Z4 == "h10", df$Z1,df$Z2)
})
When I do this I get no values in df$Z5
Upvotes: 0
Views: 41
Reputation: 521419
Just use ifelse
directly:
df$Z5 <- ifelse(df$Z3 == "h1" | df$Z4 == "h10", df$Z1, df$Z2)
df
Z1 Z2 Z3 Z4 Z5
1 AB XX h1 h10 AB
2 BA YY h2 h20 YY
3 AB YY h1 h20 AB
4 BA XX h2 h10 BA
Data:
df <- data.frame(Z1=c("AB", "BA", "AB", "BA"),
Z2=c("XX", "YY", "YY", "XX"),
Z3=c("h1","h2","h1","h2"),
Z4=c("h10","h20","h20","h10"), stringsAsFactors=FALSE)
Upvotes: 2