Reputation: 23
I am trying to write a for loop where if the cell of one matrix matches a letter it then fills a blank matrix with the entire row that matched. Here is my code
mets<-data.frame(read.csv(file="Metabolite_data.csv",header=TRUE))
full<-length(mets[,6])
A=matrix(,nrow=4930,ncol=8, byrow=T)
for (i in 1:full){
if (mets[i,6]=="A") (A[i,]=(mets[i,]))
}
If I replace the i in the if statement with a single number it works to fill that row of matrix A, however it will not fill more then one row. TIA
Upvotes: 0
Views: 61
Reputation: 10291
You might be getting problems going from data frame to matrix. It could be that just using "mets" as a matrix instead of a data frame could solve your problem, or you could use as.matrix
within your for loop. An example of the latter with made-up data since I don't have your "metabolite_data.csv":
mets <- matrix(sample(LETTERS[1:4], 80, replace = TRUE), nrow = 10, ncol = 8)
mets <- as.data.frame(mets)
A <- matrix(nrow = nrow(mets), ncol = ncol(mets), byrow = TRUE)
for(i in 1:nrow(mets)){
if(mets[i,6] == "A"){
A[i,] = as.matrix(mets[i,])
}
}
print(A)
Upvotes: 1
Reputation: 911
You may wanna try to specify ncol=dim(mets)[2]
to make sure you are providing same number of inputs to fill the matrix.
Upvotes: 0