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

arun smartpink111 at yahoo.com
Wed May 22 21:34:20 CEST 2013


Hi,
May be this helps:

test1<- test[1:5,]
test0<- test1
for(i in 1:5) test0[,i]=0
test0
#  Y X1 X2 X3 X4
#1 0  0  0  0  0
#2 0  0  0  0  0
#3 0  0  0  0  0
#4 0  0  0  0  0
#5 0  0  0  0  0
A.K.



----- Original Message -----
From: Roni Kobrosly <roni.kobrosly at gmail.com>
To: r-help at r-project.org
Cc: 
Sent: Tuesday, May 21, 2013 3:40 PM
Subject: [R] problem with "transform" and "get" functions

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)
}



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

    [[alternative HTML version deleted]]

______________________________________________
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