我想比较不同时间条件之间的绝对差异。例如,这里有两个条件(A和B),每个条件在整个时间(1:3)中都有自己的值。
df <- data.frame("condition" =c("A","B","A","A","B","B"), "time" = c(1,1,2,3,2,3) ,"value" = c(-2,3,5,1,1,6))
我如何使用dplyr创建新条件(C)作为条件A和B之间的绝对差?
expected_outcome <- data.frame("condition" =c("A","B","A","A","B","B","Diff","Diff","Diff"), "time" = c(1,1,2,3,2,3,1,2,3) ,"value" = c(-2,3,5,1,1,6,1,4,5))
要使用这三个条件创建图?例如:
ggplot(a, aes(x=time,y=value,color= condition)) +stat_summary(fun.y="mean", geom="line")
任何建议都非常感谢!
答案 0 :(得分:1)
模数列顺序:
df %>% spread(condition, value) %>%
mutate(Diff=abs(abs(A) - abs(B))) %>%
gather(condition, value, -time)
答案 1 :(得分:0)
aggregate
将达到目的:
dif <- aggregate(df$value, list(df$time), function(x) abs(diff(abs(x))))
dif <- data.frame(condition = "Diff", time = dif[,1], value = dif[,2])
dif <- rbind(df, dif)
dif
condition time value
1 A 1 -2
2 B 1 3
3 A 2 5
4 A 3 1
5 B 2 1
6 B 3 6
7 Diff 1 1
8 Diff 2 4
9 Diff 3 5