I know “pointer” is not the right terminology, but I hope it is close enough. I have the following code:
> attach(iris)
> iris$x <-0
> x
Error: object 'x' not found
It seems that after attach(), R created one object for each variable. But after I create a new variable by direct access to the data set, there’s no new object created for that variable.
How should I create a new variable for iris if I want R to create a new object for it as well?
Update: I know many R veterans suggest not to use attach(). But I need to do heavy data manipulation (hundreds of new variables), and calling transform(df,) on everyone of them sequentially would be quite cumbersome. Is it possible in R to do similar to SAS datastep, where within one data step, you can create a variable and refer to it right after:
data A;
set A;
varA = varB > 1;
varC = var A + varB;
....
run;
Update 2: One way I can think of is to use attach(), then create hundreds of arrays then cbind them before detach()
Thank you.
attach()has done nothing of the sort; it has just placed a copy of the object on the search path which allows R to look inside the object when it is looking up names.The key word above is “copy”. Which explains the behaviour you see; the copy of
irison the search path is not the one in the global workspace and you are modifying the latter not the former.Simple answer is don’t use
attach(). For adding variables to objects, look attransform()andwithin().or
To use components within objects directly, you can use
with(), e.g.I suggest you read the relevant help files for examples of usage etc.