Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
316 views
in Technique[技术] by (71.8m points)

dataframe - Mutate a new column based on multiple conditions in R

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))

enter image description here

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:

enter image description here

My code:

df %>%
  filter(city %in% c('bj', 'tj')) %>%
  mutate(direction = 'north')

Out:

enter image description here

question from:https://stackoverflow.com/questions/65916887/mutate-a-new-column-based-on-multiple-conditions-in-r

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use case_when :

library(dplyr)

df %>%
  mutate(direction = case_when(city %in% c('bj', 'tj') ~ 'north', 
                               city %in% c('sz', 'nj', 'sh') ~ 'east', 
                               city %in% c('xa', 'lz') ~ 'west', 
                               city %in% c('wh') ~ 'center', 
                               city %in% c('gz', 'sz') ~ 'south', 
                               ))

#  id city direction
#1  1   bj     north
#2  2   tj     north
#3  3   gz     south
#4  4   sz      east
#5  5   nj      east
#6  6   xa      west
#7  7   lz      west
#8  8   wh    center
#9  9   sh      east

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...