Assuming the following dataset:
df <- structure(list(id = 1:9, city = structure(c(1L, 7L, 2L, 6L, 4L,
9L, 3L, 8L, 5L), .Label = c("bj", "gz", "lz", "nj", "sh", "sz",
"tj", "wh", "xa"), class = "factor")), class = "data.frame", row.names = c(NA,
-9L))
How could create a new column direction
based on conditions:
if city
is in list ['bj', 'tj']
, then returns north
for direction
, if in ['sz', 'nj', 'sh']
returns east
, if in ['xa', 'lz']
returns west
, if in ['wh']
returns center
, if in ['gz', 'sz']
returns south
.
The expected result will like this:
My code:
df %>%
filter(city %in% c('bj', 'tj')) %>%
mutate(direction = 'north')
Out:
question from:
https://stackoverflow.com/questions/65916887/mutate-a-new-column-based-on-multiple-conditions-in-r 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…