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

David Winsemius dwinsemius at comcast.net
Thu Feb 7 20:55:58 CET 2013


On Feb 7, 2013, at 10:20 AM, 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 is nothing with that name. At the console `d$d1` is a function being applied to 'd', whereas the `get` function expects a character argument or something that evaluate to a character. This is somewhat similar to what you were attempting and syntactically succeeds:

> sapply(1:3, function(x) ifelse(d[[ paste0("d",x) ]]==1,x,d$nr))
     [,1] [,2] [,3]
[1,]    1   NA   NA
[2,]   NA    2   NA
[3,]   NA   NA    3

Notice that the '[[' function is superior in every way to the '$' function.

-- 
David.



More information about the R-help mailing list