如何使列中的某些元素彼此相等?

时间:2019-08-28 10:34:36

标签: r dataframe

col
bus
car
walk 
train
citybus
metro

我如何创建一个新的专栏,而不是公共汽车,火车,城市公交车和地铁,而是公共交通?

即输出为

 col
 public transport
 car
 walk 
 public transport
 public transport
 public transport

1 个答案:

答案 0 :(得分:2)

一个简单的replaceifelse就可以了

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