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

Petr Savicky savicky at cs.cas.cz
Fri Nov 19 22:01:30 CET 2010


On Fri, Nov 19, 2010 at 10:34:26AM -0800, wangwallace wrote:
> 
> this is a simple question, but I wasn't able to figure it out myself. 
> 
> here is the data frame:
> 
> M P Q
> 1 2 3
> 4 5 6
> 7 8 9
> 
> M, P, Q each represent a variable
> 
> I want to draw 2 random sample from each row separately to create a new data
> frame. how can I do it?

I am not sure, what you exactly mean. Can you provide an example of
the expected output?

If you consider each row as a sample of size 3 and want to use the
function sample() or sample(, replace=TRUE) to create a new sample
of the same size as a row of a new table, then in addition to the
already posted solutions you can use

  X <- matrix(1:9, ncol = 3, byrow = TRUE)

  j <- rep(seq(nrow(X)), each=2)
  Y <- matrix(, ncol=ncol(X), nrow=length(j))
  for (i in seq(nrow(Y))) {
      Y[i, ] <- sample(X[j[i], ]) # or add replace=TRUE
  }

  colnames(Y) <- c("M", "P", "Q")
  data.frame(Y)

    M P Q
  1 2 3 1
  2 1 3 2
  3 5 4 6
  4 6 4 5
  5 7 9 8
  6 8 9 7

PS.



More information about the R-help mailing list