Saturday, 10 December 2016

r - create a sample matrix from the main matrix




I want to create a sample matrix from the main one with the sam number of columns but less rows (50) I tried to use a series of loops but it didn't work:



n=nrow(data)
camp <- sample(1:n,size=50,replace=TRUE)



n<-length(camp)
c<-ncol(data)
for(i in 1:n){
t<-camp[i]
for(k in 1:c){
campione[i,k]<-data[t,k]}
}


Answer



You don't need to use loop. You just have to take random lines from your main matrix:



mat = matrix(runif(2000),ncol=20)

sample_matrix = mat[sample(1:nrow(mat),50),]

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...