[R] loop and sapply problem, help need

From: Ram H. Sharma <sharma.ram.h_at_gmail.com>
Date: Sat, 09 Apr 2011 15:30:36 -0400


Dear R experts

Sorry for this question

M1 <- 1:10

lcd1 <- c(11, 22, 33, 44, 11, 22, 33, 33, 22, 11)
lcd2 <- c(22, 11, 44, 11, 33, 11, 22, 22, 11, 22)
lcd3 <- c(12, 12, 34, 14, 13, 12, 23, 23, 12, 12)

#generating variables through sampling
 pvec <- c("PR1", "PR2", "PR3", "PR4", "PR5", "PR6", "PR7", "PR8", "PR9", "PR10")
 fun11 <- function(x){
   smpool <- c(1,2,3,3)
  x <- sample(smpool, 10, replace= TRUE)   }
 newd <- sapply (pvec, fun11)

# function to recode this new generated data
fun3 <- function(x) {

       (if ( x ==1){
      x = lcd1
    }else  if (x ==2){
        x = lcd2
    }  else if ( x ==3 ){
         x = lcd3
        } else x = NA )
                return(x)
              }

Applying the function:
pn <- sapply (newd, fun3)

I am getting 10 x 100 matrix, in contrast to 10 x 10 what I am expecting !

My objective here is to replace data points in all variables in newd with corresponding value with values vector lcd1 or lcd2 or lcd3 depending upon whether they are 1 or 2 or 3.
For example;

lcd1 <-   c(11, 22, 33, 44, 11, 22, 33, 33, 22, 11)
lcd2 <-   c(22, 11, 44, 11, 33, 11, 22, 22, 11, 22)
lcd3 <-   c(12, 12, 34, 14, 13, 12, 23, 23, 12, 12)

PR1 <- c(1, 2, 3, 2, 1, 1, 1, 2, 3, 1)

with the new
PR1n <- c(11, 11, 34, 11, 11, 22, 33, 22, 12, 11)
# as the first element of this vector is determined by PR1[1] indicator
determines whether to pick lcd1[1] or lcd2[1] or lcd3[1] element similarly for PR1[2] indicator whether to pick lcd1[2] or lcd2[2] or lcd3[2] element

The same process need to be continued other PR2 to PR10 variables. That's why I attempted to use sapply.

Thank you for your help

-- 

Ram H

	[[alternative HTML version deleted]]

______________________________________________
R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
Received on Sat 09 Apr 2011 - 20:04:33 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Sat 09 Apr 2011 - 20:30:27 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive