r - 数据操纵:收集或传播或两者兼而有之?
问题描述
我正在尝试更改我的数据框,以便我可以用一些不同的图来查看它。本质上我想比较不同的模型。这就是我所拥有的:
variable = c('A','B','C','A','B','C')
optimal = c(10,20,30,40,80,100)
control = c(15,15,15,15,15,15)
method_1 = c(11,22,28,44,85,95)
method_2 = c(9, 19,31,39,79,102)
df = data.frame(variable, optimal, control, method_1, method_2)
df
所以它看起来像这样:
variable optimal control method_1 method_2
1 A 10 15 11 9
2 B 20 15 22 19
3 C 30 15 28 31
4 A 40 15 44 39
5 B 80 15 85 79
6 C 100 15 95 102
我需要一些看起来像这样的东西:
variable A B C
1 optimal 10 20 30
2 optimal 40 80 100
3 control 15 15 15
4 control 15 15 15
5 method_1 11 22 28
6 method_1 44 85 95
7 method_2 9 19 31
8 method_2 39 79 102
我试过收集、传播和转置,但没有任何效果。有什么想法吗?感觉这应该很容易解决,但我无法理解它。提前致谢。
解决方案
你必须先走多远,然后走宽,即
library(dplyr)
library(tidyr)
df %>%
pivot_longer(-1) %>%
pivot_wider(names_from = variable, values_from = value) %>%
unnest()
name A B C
<chr> <dbl> <dbl> <dbl>
1 optimal 10 20 30
2 optimal 40 80 100
3 control 15 15 15
4 control 15 15 15
5 method_1 11 22 28
6 method_1 44 85 95
7 method_2 9 19 31
8 method_2 39 79 102
推荐阅读
- javascript - 无法解决循环 Javascript 依赖项
- java - java启动需要多少内存?
- ios - watchOS 通知安静地传递
- c# - listView.Selectedindeces[0] 未处理的异常
- python - 如何在熊猫数据框中找到混合分类变量的均值?
- javascript - 使用 Oauth 标头向 Jira REST API 发出 POST 请求 - 响应 401“匿名用户”错误
- javascript - 激活 div 上的链接
- azure - Azure VM 规模集历史数据和性能
- ruby-on-rails - 在 Rails 5 中,有没有办法修改控制器中的底层参数?还是给它一个默认值?
- c++ - 对链表数组进行合并排序