[R] 'apply' with additional class variable

Mark Ebbert Mark.Ebbert at hci.utah.edu
Sat May 21 20:23:53 CEST 2011


Dear R gurus,

I'm trying to solve what I assume is a fairly simple problem, but I'm having trouble finding the proper approach. I have a matrix where each column is some object (e.g. a car) and each row is a numeric measurement of a feature of said object (e.g. horse power, top speed, etc.). Let's also suppose that I know what make the car is (e.g. toyota, ford, etc.), stored in a separate vector. What I want to do is apply a custom function over each column of this matrix, but the function will behave differently depending on the make of the car, so each time a column is passed into my custom function, the function needs to know the make of the car. What I imagine being able to do is something like this:

carmake<-c("Toyota","Ford","Chevy")
x<-matrix(1:12,nrow=4)
colnames(x)<-c("Car1","Car2","Car3")
rownames(x)<-c("Horsepower","TopSpeed","Weight","Cost")
res<-apply(my_matrix,2,my_func,carmake)

The obvious problem with this is that I cannot know which column 'my_func' is working on, in order to know which column to get the car make from. I then thought I could try and match on column name, but when the column is passed into 'my_func' it loses the column name.

Anyway, I hope that made sense. I appreciate any help you may offer!

Mark T. W. Ebbert


More information about the R-help mailing list