Jason, Erik already offered a nice solution, but I wanted to comment on why it did not work. apply() works on arrays and, of course, matrices. When you pass a data frame to apply, it will try to coerce it to a matrix. Matrices only contain a single class of data (unlike data frames which can have separate classes for each column). The hierarchy is logical < integer < real < complex < character. Since a10 is character, everything is converted up to character. This causes sum() to fail because it is passed character data. This also explain why doit() works if you pass the data frame rows to it directly doit(myDF[1 ,]) .
You can find all this in the documentation for ?apply and ?as.matrix Cheers, Josh On Mon, Jul 19, 2010 at 12:36 PM, jd6688 <jdsignat...@gmail.com> wrote: > >>myDF = > data.frame(id=c("A10","A20"),d1=c(.3,.3),d2=c(.4,.4),d3=c(-.2,.5),d4=c(-.3,.6),d5=c(.5,-.2),d6=c(.6,-.4),d7=c(-.9,-.5),d8=c(-.8,-.6)) > >>doit=function(x)c(x[1],sum_LK_positive=sum(x[-1][x[-1]>0]),sum_LK_negative=sum(x[-1][x[-1]<0])) > >> myDF > id d1 d2 d3 d4 d5 d6 d7 d8 > 1 A10 0.3 0.4 -0.2 -0.3 0.5 0.6 -0.9 -0.8 > 2 A20 0.3 0.4 0.5 0.6 -0.2 -0.4 -0.5 -0.6 >> t(apply(myDF,1,doit)) > > > Error in sum(x[-1][x[-1] > 0]) : invalid 'type' (character) of argument: > > I changed the id=c(100,101) in myDF, it worked. are there any way to have > this working if the id=c("a10","a20")? > > Thanks, > > -- > View this message in context: > http://r.789695.n4.nabble.com/invalid-type-error-tp2294491p2294491.html > Sent from the R help mailing list archive at Nabble.com. > > ______________________________________________ > R-help@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/ ______________________________________________ R-help@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.