我有一个数据框,其中包含来自对照和实验组的多个观察结果,每个受试者都有重复。
以下是我的数据框示例:
subject cohort replicate val1 val2
A control 1 10 0.1
A control 2 15 0.3
A experim 1 40 0.7
A experim 2 45 0.9
B control 1 5 0.3
B experim 1 30 0.0
C control 1 50 0.5
C experim 1 NA 1.0
我希望将每个对照观察与每个值的相应实验对配对,以计算对之间的比率。所需的输出看起来像这样:
subject replicate ratio_val1 ratio_val2
A 1 4 7
A 2 3 3
B 1 6 0
C 1 NA 2
理想情况下,我希望通过dplyr和管道实现这一点。
答案 0 :(得分:1)
在summarize_at
和dplyr
对数据进行分组后,您可以使用val1
中的val2
功能汇总列subject
和replicate
。使用[cohort == ...]
相应地获取实验和控制组中的值以进行除法:
library(dplyr)
df %>% group_by(subject, replicate) %>%
summarize_at(vars(contains('val')),
funs("ratio" = .[cohort == "experim"]/.[cohort == "control"]))
# Source: local data frame [4 x 4]
# Groups: subject [?]
#
# subject replicate val1_ratio val2_ratio
# <fctr> <int> <dbl> <dbl>
# 1 A 1 4 7
# 2 A 2 3 3
# 3 B 1 6 0
# 4 C 1 NA 2
答案 1 :(得分:1)
我们可以通过将数据集重新整形为“广泛”格式来使用data.table
。
library(data.table)
dcast(setDT(df1), subject+replicate~cohort, value.var = c("val1", "val2"))[,
paste0("ratio_", names(df1)[4:5]) := Map(`/`, .SD[,
grep("experim", names(.SD)), with = FALSE],
.SD [, grep("control", names(.SD)), with = FALSE])][, (3:6) := NULL][]
# subject replicate ratio_val1 ratio_val2
# 1: A 1 4 7
# 2: A 2 3 3
# 3: B 1 6 0
# 4: C 1 NA 2
或者在使用'subject','replicate'分组之后,我们遍历'val'列并将'val'的'val'的相应元素除以'control'
setDT(df1)[, lapply(.SD[, grep("val", names(.SD)), with = FALSE],
function(x) x[cohort =="experim"]/x[cohort =="control"]) ,
by = .(subject, replicate)]
或者我们可以使用gather/spread
tidyr
library(dplyr)
library(tidyr)
df1 %>%
gather(Var, Val, val1:val2) %>%
spread(cohort, Val) %>%
group_by(subject, replicate, Var) %>%
summarise(ratio = experim/control) %>% spread(Var, ratio)
# subject replicate val1 val2
# <chr> <int> <dbl> <dbl>
# 1 A 1 4 7
# 2 A 2 3 3
# 3 B 1 6 0
# 4 C 1 NA 2