[R] why "object 'x' not found"?

Duncan Murdoch murdoch.duncan at gmail.com
Thu Feb 7 19:30:41 CET 2013


On 07/02/2013 1:20 PM, Winfried Moser wrote:
> Dear Listers,
>
> I try to change the structure of my data. i have an indicator-matrix and
> want to end up with a factor.
>
> i have
>
> v1 v2 v3
> 1   0   0
> 0   1   0
> 0   0   1
>
> and want
>
> v1 v2 v3  v4
> 1   0   0   1
> 0   1   0   2
> 0   0   1   3
>
> amongst other things i tried the following
>
> d <- data.frame(d1=c(1,0,0), d2=c(0,1,0), d3=c(0,0,1))
> d$nr <- NA
> sapply(1:3, function(x) ifelse(get(paste0("d$d",x))==1,x,d$nr))
>
> >From R i get the message "Object 'd$d1' not found".
> But why, it's there?
No it's not there.  There's a variable called d, but no variable called 
d$d1.  That's an expression to extract the d1 component from d.
You could parse and eval that expression, but surely it's not the right 
way to do this.  In your simple example,  using d[[x]] would work.  In a 
more complicated one, you might want something like

components <- names(d)
d[[components[x]]]

Duncan Murdoch



More information about the R-help mailing list