Reputation: 299
I have this population:
MyPopulation <- c(1:100)
and I want to create a data frame of 40 columns and 5 lines. Each column has to be a random sample of MyPopulation
, so I try this:
MySample <- data.frame(NoSample = c(1:5))
for (i in 1:40) {
MySample$i <- sample(MyPopulation,5)
}
The result is a data frame with only 1 more column (named i
) with a random sample as values.
What am I doing wrong?
Upvotes: 0
Views: 68
Reputation: 2301
You can also create a single stream of random values and then state the column dimension in a matrix with the row count being imputed:
m <- matrix(sample(1:1000, 200, replace = TRUE), ncol = 40)
df <- as.data.frame(m)
Upvotes: 1
Reputation: 102609
Maybe you can try replicate
+ as.data.frame
MySample <- as.data.frame(replicate(40,sample(MyPopulation,5)))
Upvotes: 1
Reputation: 942
The easiest solution probably would be
MyPopulation <- c(1:100)
MySample <- data.frame(NoSample = c(1:5))
for (i in 1:40) {
MySample[,i+1] <- sample(MyPopulation,5)
}
Upvotes: 1
Reputation: 10385
You cannot assign new columns that way, try MySample[paste(i)] = ...
That is you cannot assign a numeric value to a column, hence strings.
Upvotes: 1