首页 > 解决方案 > 制作单行 3x3 data.frame

问题描述

我有以下data.frame

  example.df <- data.frame(target.condition = c("congruent", "incongruent", "neutral"),
                       sdGY.2 = sample(20:30, 3, replace = T),
                       sdGX.2 = sample(20:30, 3, replace = T))

我想得到以下结果:

 congruent.sdGY.2 congruent.sdGX.2 incongruent.sdGY.2 incongruent.sdGX.2 neutral.sdGY.2 neutral.sdGX.2
1               28               29                 20                 23             27             29

我通过使用:

  test <- data.frame(congruent.sdGY.2 = example.df$sdGY.2[1], congruent.sdGX.2 = example.df$sdGX.2[1],
                 incongruent.sdGY.2 = example.df$sdGY.2[2], incongruent.sdGX.2 = example.df$sdGX.2[2],
                 neutral.sdGY.2 = example.df$sdGY.2[3], neutral.sdGX.2 = example.df$sdGX.2[3])

我想有一个更简单的方法,对吧?


谢谢!

标签: r

解决方案


您可以使用tidyverse中的tidyr和包来执行此操作。dplyr这首先更改了结构,使 sdGX.2 和 sdGY.2 在不同行的同一列中,然后将列名组合在一起,然后更改结构,使其具有许多列。

 library(dplyr)
 library(tidyr)

 example.df %>% 
   gather(ColName, ResultValue, -target.condition) %>% 
   unite(NewColName, c("target.condition", "ColName"), sep = ".", remove = TRUE) %>% 
   spread(NewColName, ResultValue)

推荐阅读