Sunday, 15 May 2011

data manipulation - How to get combinations of two factors and convert into a new factor in R -



data manipulation - How to get combinations of two factors and convert into a new factor in R -

for example, can this:

x = c(1, 2, 3, 3, 2, 1) y = c(rep("a", 3), rep("b", 3)) z= ifelse(x==1 & y=="a", "a1", ifelse(x==1 & y=="b", "b1", ifelse(x==2 & y=="a", "a2", ifelse(x==2 & y=="b", "b2", ifelse(x==3 & y=="a", "a3", "b3"))))) z = factor(z)

but tedious, there improve way?

just utilize paste0 combine vectors

factor(paste0(y, x))

or

factor(paste(y, x, sep=""))

r data-manipulation

No comments:

Post a Comment