[R] how to apply sample function to each row of a data frame?

wangwallace talenttree at gmail.com
Sun Nov 21 21:43:21 CET 2010


Hey, PS,

I revised your syntax and used it to another one of my data frames (df).

here is the data frame:

       a   b  c   A  B   C
[1,]  1   2  3   4  5   6
[2,]  7   8  9  10 11 12
[3,] 13 14 15 16 17 18

a, b, c are type I variables
A, B, C are type II variables 
each row represent the data from one subject

my purpose is to create a new data frame in which:

1) in each row, there are one random number from type I variables, and two
random numbers from type II variables

2) meanwhile, in each row, the two type II numbers have to be only those
numbers that are not corresponding to the type I number. For example, if the
type I number is 1, the type II numbers should not include 4.

3) type I number and type II numbers in each row should be all from the same
subject.

the new data frame should be like this:

       [,1] [,2] [,3]
[1,]    I     II    II
[2,]    I     II    II
[3,]    I     II    II 

Here below are the revised syntax based on yours:

     s4<-t(t(apply(df[,1:3],1,sample,1)))
     s5<-t(apply(df[,4:6],1,sample,2))
     s6<-cbind(s4,s5)

revised syntax works perfect except that it does not satisfy the following
rule I mentioned above:


2) meanwhile, in each row, the two type II numbers have to be only those
numbers that are not corresponding to the type I number. For example, if the
type I number is 1, the type II numbers should not include 4.

Do you know how to revise it to make it work? I tried different methods, but
failed. Could you please help? Again, thanks a million!!!!
-- 
View this message in context: http://r.789695.n4.nabble.com/Re-how-to-apply-sample-function-to-each-row-of-a-data-frame-tp3050933p3052752.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list