【发布时间】:2019-10-24 10:59:50
【问题描述】:
我有这些数据:
library(dplyr)
df1 <- tibble(
type = c("Animals", "Animals", "People", "People"),
type_group = c("Dogs", "Cats", "John", "Jane"),
analysis1 = c(32.7, 67.5, 34.6, 56.5),
analysis2 = c(23.7, 89.4, 45.8, 98.6),
analysis3 = c(45.7, 45.7, 23.6, 23.6),
analysis4 = c(14.4, 45.4, 98.0, 12.2))
我想在数据中添加一些新行,使其看起来像这样:
df2 <- tibble(
type = c("Animals", "Animals", "Animals diff", "People", "People", "People diff"),
type_group = c("Dogs", "Cats", "Dogs and cats" ,"John", "Jane", "John and Jane"),
analysis1 = c(32.7, 67.5, 34.8, 34.6, 56.5, 21.9),
analysis2 = c(23.7, 89.4, 65.7, 45.8, 98.6, 52.8),
analysis3 = c(45.7, 45.7, 0.0, 23.6, 23.6, 0.0),
analysis4 = c(14.4, 45.4, 31.0, 98.0, 12.2, 85.8))
新行的标题为“Animals diff”,即猫的数字减去狗的数字。同样,有一个新行称为“People diff”,即 Jane 数字减去 john 数字。
我知道执行此操作的简单方法是使用 dplyr 并将新行添加为变量并使数据更宽而不是更长。但是,该格式不适用于我想要对数据执行的操作。它特别需要采用 df2 中显示的较长格式。
我想我能做的是在dplyr 中使用mutate 创建变量以使数据更宽,然后使用reshape 使数据变长,但在玩了之后我想不出该怎么做那。关于如何进入 df2 的任何想法?
谢谢
【问题讨论】: