简体   繁体   English

如何在我的数据帧上使用完整连接并重命名具有相同名称的列 R

[英]How to use a fulljoin on my dataframes and rename columns with the same name R

I have two dataframes and they both have the exact same column names, however the data in the columns is different in each dataframe.我有两个数据框,它们都有完全相同的列名,但是每个 dataframe 中的列中的数据不同。 I am trying to join the two frames (as seen below) by a full join.我正在尝试通过完全连接来连接两个框架(如下所示)。 However, the hard part for me is the fact that I have to rename the columns so that the columns corresponding to my one dataset have some text added to the end while adding different text to the end of the columns that correspond to the second data set.但是,对我来说困难的部分是我必须重命名列,以便与我的一个数据集对应的列在末尾添加一些文本,同时在对应于第二个数据集的列的末尾添加不同的文本.

combined_df <- full_join(any.drinking, binge.drinking, by = ?)

A look at one of my df's:看看我的一个df:

Without custom function and shorter:没有自定义 function 和更短:

df <- cbind(cars, cars)
colnames(df) <- c(paste0(colnames(cars), "_any"), paste0(colnames(cars), "_binge"))

Output: Output:

> head(df)
  speed_any dist_any speed_binge dist_binge
1         4        2           4          2
2         4       10           4         10
3         7        4           7          4
4         7       22           7         22
5         8       16           8         16
6         9       10           9         10

Certainly not the most elegant way but maybe it is what you want:当然不是最优雅的方式,但也许这是你想要的:

custom_bind <- function(df1, suffix1, df2, suffix2){
  
  colnames(df1) <- paste(colnames(df1), suffix1, sep = "_")
  colnames(df2) <- paste(colnames(df2), suffix2, sep = "_")
  
  df <- cbind(df1, df2)
  return(df)
}

custom_bind(cars, "any", cars, "binge")

I made it as a function in case you want to do it with other tables.我把它做成 function 以防你想和其他桌子一起做。 If not then it is not necessary.如果没有,则没有必要。

Output: Output:

> head(custom_bind(cars, "any", cars, "binge"))
  speed_any dist_any speed_binge dist_binge
1         4        2           4          2
2         4       10           4         10
3         7        4           7          4
4         7       22           7         22
5         8       16           8         16
6         9       10           9         10

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM