1
votes

all

I'm new to R. I try many ways and still cannot solve it. Can anyone help to check??

I am trying to produce 3 times 100 random values that follow a chisquare distribution. Console says ''number of items to replace is not a multiple of replacement length''. Any hint to fix it??

for(i in 1:3) {
  x1[i] <- rchisq(100, df=2)
  n1[i] <- length(x1[i])
}
2
Is this what you're trying to do? for(i in 1:3){ x1 <- rchisq(100, df=2) n1 <- length(x1) print(x1[n1]) } - jared_mamrot
Try using double-square brackets: x1[[i]] <- rchisq(100, df=2) - Edward

2 Answers

0
votes

It depends on what containers you want to use. There are two containers that come to mind, either a list or matrix.

# list format
x1 = list();
n1 = vector();
for(i in 1:3) {
  x1[[i]] <- rchisq(100, df=2)
  n1[i] <- length(x1[[i]])
}

note the double brackets [[i]] as mentioned in the comments

# matrix format
x1 = matrix(NA, nrow = 100, ncol = 3)
n1 = vector();
for(i in 1:3) {
  x1[,i] <- rchisq(100, df=2)
  n1[i] <- length(x1[,i])
}
0
votes

As an explanation for your problem: You are trying to store a vector of 100 elements into a single element, the ith element, of a vector, x1. To illustrate, you could put a vector of values into a vector of the same length:

x <- rnorm(6, 0, 1)
x[1:3] <- c(1,2,3)
x
## [1]  1.0000000  2.0000000  3.0000000 -0.8652300  1.3776699 -0.8817483

You could to store them into a list, each element of a list is a vector that can be of any length. You will need double square brackets.

x1 <- list()
for(i in 1:3) {
  x1[[i]] <- rchisq(100, df=2)
  n1[i] <- length(x1[[i]])
}

Lists and vectors are different types of data structures in R, you can read a lot about them in advanced R.