[R] problem with "transform" and "get" functions

David Winsemius dwinsemius at comcast.net
Wed May 22 01:54:28 CEST 2013


On May 21, 2013, at 12:40 PM, Roni Kobrosly wrote:

> Hello, I'm having a problem using the "transform" and "get" functions. I'm
> probably making a dumb mistake, and I need help!
> 
> I start by making a small simulated dataset. I save the names of the
> variables in "var.names." Without getting into the details of it, I have to
> create a custom function to perform some statistics. As part of this, I
> need to sequentially set all variables in the dataset (one at a time) to a
> value of 0. I tried using the "get" function, to automate this (I need to
> automate this because my real dataset has 100's of variables). However, I
> get the following error message:
> 
> "
> Error: unexpected '=' in:
> "{
> test0 <- transform(test, (get(predictor.names[i])) ="
>> }
> Error: unexpected '}' in "}"
>> 
> 
> Here is my code:
> 
> 
> 
> n<-200
> set.seed(111)
> X1 <- rbinom(n,1,0.4)
> X2 <- rbinom(n,1,0.5)
> X3 <- rbinom(n,1,0.5)
> X4 <- rbinom(n,1,(0.5 + 0.2*X1 - 0.3*X2 + 0.005*X3))
> Y <- rnorm(n,(3 + X1 + 0.3*X2 + 0.1*X3 + 0.05*X4),.4)
> data.frame(Y,X1,X2,X3,X4) -> test
> 
> var.names <- colnames(test)
> 
> for (i in (1:5))
> {
> test0 <- transform(test, (get(var.names[i])) = 0)

There is no `get<-` function. You need to use assign.


> }
> 
> 
> 
> ## NO ERROR MESSAGE WHEN I DON'T USE "GET", AND INSTEAD DO IT EXPLICITLY
> test0 <- transform(test, X1 = 0)
> 

Right. There is a `<-` function


> 	[[alternative HTML version deleted]]
> 
Please learn to post in plain text. It's really quite easy.

-- 

David Winsemius
Alameda, CA, USA



More information about the R-help mailing list