[R] looping through columns in a matrix or data frame

arun smartpink111 at yahoo.com
Wed Jan 1 22:35:53 CET 2014

May be this helps:

Using your function:

#[1] 2 3
#[1] 3


 for(i in 1:ncol(test)){
#[1] 2 3
#[1] 3


Hi, I'm trying to figure out how to loop through columns in a matrix or 
data frame, but what I've been finding online has not been very clear. 
I've written the following simple function that I can use on a column to extract all values that are less than a specified number. Consider the 
following example using that function to extract all values less than 4 
from column1 of the table "test" 

> less <- function(x,y){print(x[which(x < y)])} 

> test 
  column1 column2 
1       2       3 
2       3       4 
3       4       5 

> less(test[,1],4) 
[1] 2 3 

What I want to do is loop that function over all the columns
 in the table. Note: I realize that this is a silly example and there 
are better ways to do this particular function in R, so please don't 
respond with better ways to extract values less than a given number. The
 question that I am interested in is merely how do I loop over the 
columns. If you could respond by modifying my silly function so that it 
will loop, that would be the most helpful response. Thanks for the 

More information about the R-help mailing list