2

我有一个看起来像这样的data.frame:(我的真实数据框更大):

df <- data.frame(A=c("a","b","c","d","e","f","g","h","i"), 
               B=c("1","1","1","2","2","2","3","3","3"), 
               C=c(0.1,0.2,0.4,0.1,0.5,0.7,0.1,0.2,0.5))

> df
  A B   C 
1 a 1 0.1 
2 b 1 0.2 
3 c 1 0.4 
4 d 2 0.1 
5 e 2 0.5 
6 f 2 0.7 
7 g 3 0.1 
8 h 3 0.2 
9 i 3 0.5 

我想添加几个 n 列(类似于permutations),其中列 D 将是一个随机值,df$C但该值只能从具有 dame 值的那些行中选取,df$B所需输出的示例是:

df <- data.frame(A=c("a","b","c","d","e","f","g","h","i"), 
               B=c("1","1","1","2","2","2","3","3","3"), 
               C=c(0.1,0.2,0.4,0.1,0.5,0.7,0.1,0.2,0.5),
               D=c(0.2,0.2,0.1,0.5,0.7,0.1,0.5,0.5,0.2))

> df
  A B   C   D
1 a 1 0.1 0.2
2 b 1 0.2 0.2
3 c 1 0.4 0.1
4 d 2 0.1 0.5
5 e 2 0.5 0.7
6 f 2 0.7 0.1
7 g 3 0.1 0.5
8 h 3 0.2 0.5
9 i 3 0.5 0.2

我试过plyr包,但我的方法不能正常工作:

ddply(df, levels(.(B)), transform, D=sample(C))

我还考虑过基于拆分数据帧df$B,然后使用函数在每个数据帧中添加列,lapply但是我不知道如何选择df$B,

非常感谢

4

1 回答 1

2

不需要plyrave就可以了。

transform(df, D=ave(C, B, FUN=function(b) sample(b, replace=TRUE)))
于 2013-06-20T16:33:09.690 回答