按R中的特定值完全重新排列数据帧
我有一个大型的数据框架,它包含了许多会话的测试值,我想根据会话号重新安排它的结构 我如何从这个“转换”数据帧 对这个 编辑: 这是解决这个问题的代码按R中的特定值完全重新排列数据帧,r,R,我有一个大型的数据框架,它包含了许多会话的测试值,我想根据会话号重新安排它的结构 我如何从这个“转换”数据帧 对这个 编辑: 这是解决这个问题的代码 library(tidyverse) df2 <- df %>% pivot_wider(names_from = session, values_from=c(weight, active, inactive, reward, beam_breaks)) 库(tidyverse) df2% pivot\u更宽(na
library(tidyverse)
df2 <- df %>%
pivot_wider(names_from = session,
values_from=c(weight, active, inactive, reward, beam_breaks))
库(tidyverse)
df2%
pivot\u更宽(name\u from=会话,
值_from=c(重量、活动、非活动、奖励、横梁_断裂))
正如评论中所建议的,您必须重塑数据。您显示的数据看起来是长格式的,因此您必须转换为宽格式。下面是使用tidyverse
函数和虚拟数据更接近所需输出的代码:
library(tidyverse)
#Data
df <- structure(list(fr = c(1, 1, 1, 1, 1, 1), session = c(1L, 1L,
1L, 2L, 2L, 2L), subject = c(1L, 2L, 3L, 1L, 2L, 3L), group = structure(c(1L,
1L, 2L, 1L, 1L, 2L), .Label = c("heroin", "saline"), class = "factor"),
boxnum = structure(c(1L, 2L, 3L, 1L, 2L, 3L), .Label = c("Box1",
"Box2", "Box3"), class = "factor"), weight = c(268, 265,
255, 260, 221, 244), active = c(104, 58, 67, 59, 52, 75),
inactive = c(15, 15, 11, 11, 12, 16), reward = c(25, 37,
20, 28, 36, 22), beam_breaks = c(499265, 459925, 451156,
520617, 536350, 478565)), class = "data.frame", row.names = c(NA,
-6L))
库(tidyverse)
#资料
如果你正在寻找一种叫做“从长到宽重塑”的东西。请参见重塑()
或tidyr::pivot\u wider()
。R数据框不支持分层列,不建议重复colnames。谢谢!崔奇没听说过pivot\u更宽。那很有效!非常感谢。
#Code
df2 <- df %>% pivot_wider(names_from = session,
values_from=c(weight,active,inactive,reward,beam_breaks))
# A tibble: 3 x 14
fr subject group boxnum weight_1 weight_2 active_1 active_2 inactive_1 inactive_2 reward_1
<dbl> <int> <fct> <fct> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 1 1 hero~ Box1 268 260 104 59 15 11 25
2 1 2 hero~ Box2 265 221 58 52 15 12 37
3 1 3 sali~ Box3 255 244 67 75 11 16 20
# ... with 3 more variables: reward_2 <dbl>, beam_breaks_1 <dbl>, beam_breaks_2 <dbl>