I have a data frame with two factors, like this one:
data <- data.frame(
x = factor(rep(letters[1:3], 2)),
y = factor(rep(c('z','x','y'), each=2), c('z','x','y'))
)
data
x y
1 a z
2 b z
3 c x
4 a x
5 b y
6 c y
I want to turn all the ys for which x is a into NAs. So I try:
factor(ifelse(data$x=='a', NA, as.character(data$y)))
<NA> z x <NA> y y
Levels: x y z
to get different levels order than in original data, which was:
data$y
z z x x y y
Levels: z x y
Can you suggest any way to keep original ordering, other than brute force like this:
factor(ifelse(data$x=='a', NA, as.character(data$y)), c('z','x','y'))
<NA> z x <NA> y y
Levels: z x y