r - 制作单行 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])
我想有一个更简单的方法,对吧?
谢谢!
解决方案
您可以使用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)
推荐阅读
- javascript - React Native:出错时将axios重定向到不同的地址
- xml - 使用 xsl 删除命名空间声明
- java - 与 Spring 和 Thymeleaf 的注销链接;发布错误
- angular - 茉莉花单元测试“在afterAll中引发了错误”
- dialog - Angular6 Material Dialog防止在按下回车时关闭
- neo4j - Neo4j - 图表数据
- google-oauth - 传递多个域以限制 - 在 Google OAuth 中的“hd”参数中
- c# - 如何在winforms图片框中每次单击鼠标时绘制小字符(x或z)
- python - pyenv 失败:ModuleNotFoundError: No module named '_ctypes' 错误
- php - 在雄辩的 laravel 中具有 AND 条件的产品过滤器