根据列表中的值将列添加到数据框中

时间:2013-06-24 23:32:04

标签: r

我有一个如下所示的数据框:

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

包含名称与df$B匹配的元素的列表,即这些值是来自df$B的值的排列,这是一个示例:

 ll <- list('1'=c(0.1,0.1,0.4,0.2,0.1,0.4),
            '2'=c(0.1,0.1,0.5,0.7,0.5,0.7),
            '3'=c(0.1,0.1,0.2,0.2,0.2,0.5))

有没有办法在数据框df中创建与列表df$Bll的值相对应的新列,但同时它们采样 ll的值? 这是一个理想的输出,以获得更好的解释

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

1 个答案:

答案 0 :(得分:1)

喜欢这样:

cbind(df, t(sapply(df$B, function(i, l) sample(l[[as.character(i)]]), l = ll))

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

或者,如果我误解了,请澄清“置换”。