I have a data.frame df
where the column x is populated with integers (1-9). I would like to update columns y and z based on the value of x as follows:
if x is 1,2, or 3 | y = 1 ## if x is 1,4, or 7 | z = 1
if x is 4,5, or 6 | y = 2 ## if x is 2,5, or 8 | z = 2
if x is 7,8, or 9 | y = 3 ## if x is 3,6, or 9 | z = 3
Below is a data.frame with the desired output for y
and z
df <- structure(list(x = c(1L, 2L, 3L, 3L, 4L, 2L, 1L, 2L, 5L, 2L,
1L, 6L, 3L, 7L, 3L, 2L, 1L, 4L, 3L, 2L), y = c(1L, 1L, 1L, 1L,
2L, 1L, 1L, 1L, 2L, 1L, 1L, 2L, 1L, 3L, 1L, 1L, 1L, 2L, 1L, 1L
), z = c(1L, 2L, 3L, 3L, 1L, 2L, 1L, 2L, 2L, 2L, 1L, 3L, 3L,
1L, 3L, 2L, 1L, 1L, 3L, 2L)), .Names = c("x", "y", "z"), class = "data.frame", row.names = c(NA,
-20L))
I can write a for-loop with multiple if statements to fill y
and z
row by row. This doesn't seem very r: it is not vectorized. Is there a method to specify what numeric values will correspond to new numeric values? Like a map or key to indicate which values will become based on the previous values.