将两个列名不同的 dfs 组合起来,然后融化 [英] Combine two dfs with different column names and then melt
本文介绍了将两个列名不同的 dfs 组合起来,然后融化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想合并两个数据框,但根据以下内容将它们融合到不同的列中:
I want to combine two data frames but melt them into different columns based on below:
treatment<-c('control','noise')
weight<-c(0.01872556,0.01575400)
sd<-c(0.008540041,0.007460524)
df1<-data.frame(treatment,weight,sd)
treatment2<-c('control','noise')
area<-c(0.79809444,0.68014667)
sd2<-c(0.337949414,0.294295847)
df2<-data.frame(treatment2,area,sd2)
我想组合它们并创建一个看起来像这样的数据框:
And I wanted to combine them and create a data frame which should look like this:
治疗 | 变量 | 总和 | sd |
---|---|---|---|
控制 | 区域 | 0.79809444 | 0.337949414 |
噪音 | 区域 | 0.68014667 | 0.294295847 |
控制 | 重量 | 0.01872556 | 0.008540041 |
噪音 | 重量 | 0.01575400 | 0.01575400 |
我尝试了各种方法,搜索了各种方法,最终将每个数据框导出到 csv 中,然后将它们组合到 excel 中,重新导入到 R 中进行分析.
I tried this various ways, googled various ways and ended up exporting each data frame into a csv then combining them in excel, re-importing into R for analysis.
有更简单的解决方案吗?
Is there a simpler solution?
推荐答案
你可以使用
library(tidyr)
library(dplyr)
df2 %>%
rename(sd = sd2, treatment = treatment2) %>%
pivot_longer(area, names_to = "var", values_to = "sum") %>%
bind_rows(pivot_longer(df1, weight, names_to = "var", values_to = "sum")) %>%
select(treatment, var, sum, sd)
得到
# A tibble: 4 x 4
treatment var sum sd
<chr> <chr> <dbl> <dbl>
1 control area 0.798 0.338
2 noise area 0.680 0.294
3 control weight 0.0187 0.00854
4 noise weight 0.0158 0.00746
这篇关于将两个列名不同的 dfs 组合起来,然后融化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文