I've been trying to work through this small R prompt, but can't figure out what I'm doing wrong. I haven't used R in a few years, so I'm trying to get back into the flow of things. Here's my code:
y <- 5
loopValues <- c(100,200,500,800,1000)
dataframesq3 <- vector("list", y)
for (i in 1:y) {
for (j in loopValues){
dataframesq3[[i]] <- data.frame(replicate(10,sample(0:1,j,rep=TRUE)))
}
}
print(dataframesq3)
Currently, I get 5 data frames with 10 columns each and 1000 rows each instead of one of reach of the 5 above links.
CodePudding user response:
You can just refer to the index of loopValues
with i
and use a single loop:
y <- 5
loopValues <- c(100,200,500,800,1000)
dataframesq3 <- vector("list", y)
for (i in 1:y) {
dataframesq3[[i]] <- data.frame(replicate(10,sample(0:1,loopValues[i],rep=TRUE)))
}
print(dataframesq3)
CodePudding user response:
Here's an approach without a loop:
loopValues <- c(100,200,500,800,1000)
dataframesq3 <- lapply(loopValues, function(x) data.frame(replicate(10, rbinom(x, 1, .5))))