列
col
bus
car
walk
train
citybus
metro
我如何创建一个新的专栏,而不是公共汽车,火车,城市公交车和地铁,而是公共交通?
即输出为
col
public transport
car
walk
public transport
public transport
public transport
答案 0 :(得分:2)
一个简单的replace
或ifelse
就可以了
df$new_col <- replace(df$col, df$col %in% c("bus", "train", "citybus", "metro"),
"public transport")
df
# col new_col
#1 bus public transport
#2 car car
#3 walk walk
#4 train public transport
#5 citybus public transport
#6 metro public transport
使用ifelse
df$new_col <- ifelse(df$col %in% c("bus", "train", "citybus", "metro"),
"public transport", df$col)
或
df$new_col <- df$col
df$new_col[df$col %in% c("bus", "train", "citybus", "metro")] <- "public transport"
数据
df <- structure(list(col = c("bus", "car", "walk", "train", "citybus",
"metro")), class = "data.frame", row.names = c(NA, -6L))