[R] vector output loop or function

Dennis Murphy djmuser at gmail.com
Thu Sep 1 14:23:53 CEST 2011


Hi:

Here's one approach:

X1 <- sample(1:4, 10, replace = TRUE, prob = c(0.4, 0.2, 0.2, 0.2))

foo <- function(x) {
   m <- matrix(NA, nrow = length(x), ncol = length(x))
   m[, 1] <- x
   idx <- seq_len(length(x))
   for(j in idx[-1]) {
      k <- sample(idx, 2)
      x <- replace(x, k, 5)
      m[, j] <- x
     }
  m
 }

foo(X1)

# For an example I ran, I got
> foo(X1)
      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
 [1,]    4    4    4    4    4    4    4    4    4     4
 [2,]    2    2    2    2    5    5    5    5    5     5
 [3,]    4    4    4    4    4    4    4    5    5     5
 [4,]    1    1    1    1    1    1    1    5    5     5
 [5,]    1    5    5    5    5    5    5    5    5     5
 [6,]    2    2    2    2    2    2    2    2    5     5
 [7,]    3    3    5    5    5    5    5    5    5     5
 [8,]    4    4    4    4    5    5    5    5    5     5
 [9,]    3    5    5    5    5    5    5    5    5     5
[10,]    4    4    4    5    5    5    5    5    5     5

The function returns a matrix (which should make the function a bit
faster). You can always convert it to a data frame and assign column
names to it afterward, or you can modify the function to return a data
frame rather than a matrix (as.data.frame(m)   in the last line).

HTH,
Dennis

On Wed, Aug 31, 2011 at 6:10 PM, Nilaya Sharma <nilaya.sharma at gmail.com> wrote:
> Dear all
>
> Sorry for simple question:
>
> I want to put the following option into look as number of X is large 1000
> variables
>
> X1 <- sample(c(1,2, 3, 4),10, replace = T, prob = c(0.4, 0.2, 0.2, 0.2))
>
> cv1 <- round(runif(2, 1, 10))
>
>
> # X2 is copy of X1
>
> X2 <- X1
>
> # now X2 is different in cv1 random positions
>
> X2[cv1] <-   5
>
> cv2 <- round(runif(2, 1, 10))
>
>
> # X3 is copy of X2
>
> X3 <- X2
>
> X3[cv2] <-   5
>
> ….
>
> So on till X10
>
> mydf <- data.frame ( X1, X2, X3, X4, X5, X6, X7, X8, X9, X10)
>
>
>
>  The basic idea is the X2 is like X1 but is different at two positions where
> the normal value is replaced with 5, the position is defined by cv1 . The
> process is repeated till the last variable.
>
>
>
> I tried several way. One of unsuccessful function:
>
>  v = 2:10
>
>  mufun3 <- function(v, x){
>
>            x[,v] <- x[,v-1]
>
>            cv1 <- round(runif(3, 1, 10))
>
>            }
>
>  mufun3 (v, X1)
>
>
> Thank you for the help
>
>
> NIL
>
>        [[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.
>
>



More information about the R-help mailing list