如果您不想丢失任何数据,请使用paste
library(dplyr)
df%>% mutate(Place = paste(Place_English, Place_French),
Plane = paste(Plane_English, Plane_French),
across(Place_English:Plane_French, ~NULL)) ## last line to remove unnecessary columns
或coalesce,如果你想摆脱NAs
df%>% mutate(Place = coalesce(Place_English, Place_French),
Plane = coalesce(Plane_English, Plane_French),
across(Place_English:Plane_French, ~NULL)) ## last line to remove unnecessary columns
如果您想组合超过 2 个列,请使用来自 tidyr 的 unite。根据您的喜好设置na.rm
library(tidyr)
df %>%
unite("Place", colnames(df)[grepl(pattern = "Place", colnames(df))] , remove = T, sep = " ", na.rm = TRUE) %>% ## all cols including "Place" in name
unite("Plane", colnames(df)[grepl(pattern = "Plane", colnames(df))] , remove = T, sep = " ", na.rm = TRUE) ## all cols including "Plane" in name
library(tidyr)
cols_to_paste <- colnames(df[,]) ## to choose only sepecified cols i.e. df[,15:25] or df[,c(15,18,20,25)]
df %>%
unite('Place', cols_to_paste[grepl(pattern = 'Place', cols_to_paste)] , remove = T, sep = " ", na.rm = TRUE) %>% ## all cols including "Place" in name
unite('Plane', cols_to_paste[grepl(pattern = 'Plane', cols_to_paste)] , remove = T, sep = " ", na.rm = TRUE) ## all cols including "Plane" in name