假设我有一个看起来像这样的数据框
dd <- read.table(header = TRUE, text = "ID week1_t week1_a week2_t week2_a
1 12 22 17 4
1 15 32 18 5
1 24 12 29 6
2 45 11 19 8
2 23 33 20 10")
是否有一种简单的方法可以创建一个week1_d列,一个week2_d列,依此类推每周,这是基于week1_t和week1_a之间的差异?或者我是否必须手动构建“差异”列?
预期输出如下:
dd <- read.table(header = TRUE, text = "ID week1_t week1_a week2_t week2_a week1_d week2_d
1 12 22 17 4 10 -13
1 15 32 18 5 17 -13
1 24 12 29 6 -12 -23
2 45 11 19 8 -34 -11
2 23 33 20 10 10 -10 ")
实际上,大约有30周,所以我试图避免手动执行此操作。我正在考虑for循环每周的运行,并且grepping匹配week +(循环索引)的列。有没有更好的方法呢?
答案 0 :(得分:5)
从“整洁数据”的角度来看,您的问题是您在列名中编码(多个!)数据:周数和字母代表的数字。我会转换为长格式,其中week是一列,定义d = a - t
,并且(如果需要)转换回宽格式。但是我可能会把它保留为长格式,因为如果你想做任何其他操作,它们可能更容易在长数据上实现(更多操作,建模,绘图......)。
library(tidyr)
library(dplyr)
long = dd %>%
mutate(real_id = 1:n()) %>%
gather(key = key, value = value, starts_with("week")) %>%
separate(key, into = c("week", "letter")) %>%
spread(key = letter, value = value) %>%
mutate(d = a - t)
head(long)
# ID real_id week a t d
# 1 1 1 week1 22 12 10
# 2 1 1 week2 4 17 -13
# 3 1 2 week1 32 15 17
# 4 1 2 week2 5 18 -13
# 5 1 3 week1 12 24 -12
# 6 1 3 week2 6 29 -23
wide = gather(long, key = letter, value = value, a, t, d) %>%
mutate(key = paste(week, letter, sep = "_")) %>%
select(-week, -letter) %>%
spread(key = key, value = value)
wide
# ID real_id week1_a week1_d week1_t week2_a week2_d week2_t
# 1 1 1 22 10 12 4 -13 17
# 2 1 2 32 17 15 5 -13 18
# 3 1 3 12 -12 24 6 -23 29
# 4 2 4 11 -34 45 8 -11 19
# 5 2 5 33 10 23 10 -10 20
答案 1 :(得分:3)
我们split
周&#39;在将dd[-1]
后缀移除到names
后,数据集的sub
列(list
),获取两列之间的差异并指定list
}元素在&#39; dd&#39;。
lst <- lapply(split.default(dd[-1],
sub("_.*", "", names(dd)[-1])), function(x) x[2]-x[1])
dd[paste0("week_", seq_along(lst), "d")] <- lapply(lst, unlist, use.names=FALSE)
dd
# ID week1_t week1_a week2_t week2_a week1_d week2_d
#1 1 12 22 17 4 10 -13
#2 1 15 32 18 5 17 -13
#3 1 24 12 29 6 -12 -23
#4 2 45 11 19 8 -34 -11
#5 2 23 33 20 10 10 -10
如果列是交替的,即&quot; week1_t&#39;然后是&#39; week1_a&#39;,然后&#39; week2_t&#39;,然后是&#39; week2_a&#39;等。
Un1 <- unique(sub("_.*", "", names(dd)[-1]))
i1 <- c(TRUE, FALSE)
dd[paste0(Un1, "_d")] <- dd[-1][!i1]- dd[-1][i1]
dd
# ID week1_t week1_a week2_t week2_a week1_d week2_d
#1 1 12 22 17 4 10 -13
#2 1 15 32 18 5 17 -13
#3 1 24 12 29 6 -12 -23
#4 2 45 11 19 8 -34 -11
#5 2 23 33 20 10 10 -10