[R] 'Apply' giving me errors

Kenn Konstabel lebatsnok at gmail.com
Fri Oct 21 13:10:39 CEST 2011


On Fri, Oct 21, 2011 at 3:09 AM, kickout <kyle.kocak at gmail.com> wrote:
> So i have a simple function:
>
> bmass=function(y){
> weight=y$WT*y$MSTR
> return(bio)
> }

But this just returns "bio" and since an object with that name is not
defined in the function, it will be looked up in the global
environment (workspace) and if it's not there either, you will get
Error: object 'bio' not found. So even if you could fix the apply
"issue" it would still not work. But Uwe Ligges showed you don't need
apply to do what you seem to intend here, final$WT*final$MSTR should
work.

But if you do insist on apply for whatever reason then ... apply
converts X (the first argument) to a matrix so you can't use the $
operator any more. The column names are preserved though, so what you
could do is

bmass <- function(y) y["WT"] * y["MSTR"]
apply(final, 1, bmass)

> And want to apply to a whole bunch of rows in my data.frame:
>
> final1=apply(final,1,yldbu)

What is yldbu? I suppose you meant the function you defined above?

Kenn

>
>
> BUT...recieve the following error:
> "Error in y$WT : $ operator is invalid for atomic vectors"
>
>
> However when i try:
>> final[1,]$WT*final[1,]$MSTR
> [1] 156.3
>
>
> It gives me the correct answer....what is apply not liking in my code?
>
> Thanks
>
>
>
> --
> View this message in context: http://r.789695.n4.nabble.com/Apply-giving-me-errors-tp3923880p3923880.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> 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.
>



More information about the R-help mailing list