簡體   English   中英

如何在我的數據幀上使用完整連接並重命名具有相同名稱的列 R

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

我有兩個數據框,它們都有完全相同的列名,但是每個 dataframe 中的列中的數據不同。 我正在嘗試通過完全連接來連接兩個框架(如下所示)。 但是,對我來說困難的部分是我必須重命名列,以便與我的一個數據集對應的列在末尾添加一些文本,同時在對應於第二個數據集的列的末尾添加不同的文本.

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

看看我的一個df:

沒有自定義 function 和更短:

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

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

當然不是最優雅的方式,但也許這是你想要的:

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

我把它做成 function 以防你想和其他桌子一起做。 如果沒有,則沒有必要。

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