Tell me more ×
Cross Validated is a question and answer site for statisticians, data analysts, data miners and data visualization experts. It's 100% free, no registration required.

I'm looking to create a script to convert a matrix of species abundance e.g:

species abundance matrix

into two vectors e.g:

vectors


If you feel there is no easy answer to this and that it would be easier to do in excel or open office calc (or another program), please let me know.

share|improve this question
1  
There is an easy answer to this, but it is not clear if the matrix is already an object in R (what kind of object?) or if you also need help importing the data. Also, this question should be moved to Stack Overflow by a moderator. – Roland Sep 24 '12 at 13:32
Thanks Roland. This problem has now been solved elsewhere. – Ben Gillespie Sep 24 '12 at 14:02

closed as off topic by cardinal, Andy W, mpiktas, Bernd Weiss, chl Sep 24 '12 at 14:09

Questions on Cross Validated are expected to relate to statistics within the scope defined in the FAQ. Consider editing the question or leaving comments for improvement if you believe the question can be reworded to fit within the scope. Read more about closed questions here.

1 Answer

How about something like this:

 #I typed in some data to make sure it works:
 species1 = c(5,4,NA,NA)
 species2 = c(NA,NA,5,NA)
 species3 = c(4,4,NA,NA)
 species4 = c(NA,4,NA,6)

 data.matrix = rbind(species1,species2, species3, species4)



 #lets say your original dataframe is called data.matrix 
 #and your new data set is called data.list
 #the number of rows in your new data set is the number of values that are not NA:
 rows = length(data.matrix[!is.na(data.matrix)])
 data.list = matrix(nrow = rows, ncol = 2)
 k = 1 #an index variable for the new data set
 for(j in 1:ncol(data.matrix)){
   for(i in 1:nrow(data.matrix)){
     if(is.na(data.matrix[j,i]) == FALSE){
       #store the site number
       data.list[k,1] = i
       #store the species number
       data.list[k,2] = j
       k = k + 1
     }
   }
 }
 #sort the data by the first column
 data.list = data.list[order(data.list[,1]),]

Output:

data.list [,1] [,2]

 [1,]    1    1
 [2,]    1    3
 [3,]    2    1
 [4,]    2    3
 [5,]    2    4
 [6,]    3    2
 [7,]    4    4

I think this question is OK in the stats section of stack exchange. I've noticed that this is a really common data transform for people in Biology to prepare their data for statistical analysis.

share|improve this answer
This can be much better solved in R without loops. – Roland Sep 24 '12 at 14:44

Not the answer you're looking for? Browse other questions tagged or ask your own question.