R有条件地将重复的矢量作为列映射到数据帧

时间:2015-03-29 09:56:23

标签: r dplyr

我想从原始值中减去平均值的向量。我想不通,如何映射相应的手段和价值条件。到目前为止,我尝试正确安排值,但即使在那里我也失败了。

library("reshape")
require('plyr')
require("dplyr")

数据框:

    n  <-  as.factor(rep(c(1:16), times=2)) 
s  <-  as.factor(rep(c("ja","nein"), each=8, times=2))
b  <-  as.factor(rep(c("red", "green","blue", "pink"),times=8)) 
zahl <- runif(32)
df  <-  data.frame(n, s, b, zahl)

作为专栏的手段:

df.mean <- melt(data.frame(cast(df, b~s, mean)), id=1, measured=2:3)

我的错误版本:

df.final <- df%>%
  mutate(r=1:32,
         trial=rep(1:2, each=16))%>%
  #arrange(r,n,trial,s,b)%>%   # this does't arrange the "ja, nein" eaqual to the means
  mutate(mean.bs=rep(df.mean[,3], times=4),
         diff=zahl-mean.bs)

结果应该是:

    n    s     b zahl  trial mean.bs  diff
1   1   ja   red 0.49     1  0.8025 -0.3125
2   2   ja green 0.59     1  0.6200 -0.0300
3   3   ja  blue 0.97     1  0.3175  0.6525
4   4   ja  pink 0.04     1  0.5225 -0.4825
5   9 nein   red 0.x      1  0.4775  0.x
6  10 nein green 0.x      1  0.3975  0.x
7  11 nein  blue 0.x      1  0.5625  0.x
8  12 nein  pink 0.x      1  0.3925  0.x
9   5   ja   red 0.x      1  0.8025 -0.x   # here means repeat
10  6   ja green 0.x      1  0.6200 -0.x
...

也许有更精确的方法可以做到这一点? (有条件......)

谢谢你!

2 个答案:

答案 0 :(得分:1)

好的,我不是100%确定你想要达到的目标(在使用随机数据之前设置seed是一个好主意),但试试这个(在{{{ 1}}行:

df.mean <- ...

答案 1 :(得分:1)

我们可以在mutate本身

中找到差异
library(dplyr)
df %>%
    group_by(b,s) %>% 
     mutate(mean.bs= mean(zahl), diff= zahl-mean.bs)