简体   繁体   中英

Add columns to a dataframe based on values from a list

I have a dataframe that looks like this:

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

And a list with elements which names match to df$B , ie, these values are permutations of values from df$B , here is an example:

 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))

Is there any way to create new columns in the dataframe df that corresponds to the values of df$B in list ll but at the same time they are sampled values from ll ? Here is a desired output for a better explanation

> 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 

Like this maybe:

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

Or please clarify "permuted" if I misunderstood.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM