[R] 'apply' with additional class variable

Joshua Wiley jwiley.psych at gmail.com
Sat May 21 20:57:13 CEST 2011


Hi Mark,

Is there a reason you cannot simply include the make of the car along
with all the other data?  Using your example:

cbind(as.data.frame(t(x)), carmake)

then instead of applying across columns, apply across rows, and have
your custom function decide what to do based on the column named
"carmake".  Alternately, if you will be dealing with the same makes of
cars a lot and are willing to do something a bit more involved, you
could consider defining custom classes for each car make, make your
function generic, and then create methods for it to match the
different car makes.

Cheers,

Josh


On Sat, May 21, 2011 at 11:23 AM, Mark Ebbert <Mark.Ebbert at hci.utah.edu> wrote:
> 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
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



-- 
Joshua Wiley
Ph.D. Student, Health Psychology
University of California, Los Angeles
http://www.joshuawiley.com/



More information about the R-help mailing list