Reputation: 4930
I am using R to scrub data. I have a dataset with 1,000s of columns all of which have some modification. I find the $
operator makes my code unreadable. I like to do data steps with the with
command, so that all the elements of the data frame are locally scoped (forgive my near complete ignorance of computer science here). However, after all is done, I would like to return all the variables I wrote in the with
step and possibly overwrite whichever ones I pulled in earlier. I notice the ls()
command only looks at vars defined inside the with
step, but how can I concatenate them into a dataframe?
As an example of desired output:
set.seed(123)
myDat <- data.frame('x'=rnorm(3))
y <- with(myDat, {
xgt0 <- x > 0
x2 <- x^2
foo()
})
print(y)
x1 xgt0 x2
1 -0.5604756 FALSE 0.31413295
2 -0.2301775 FALSE 0.05298168
3 1.5587083 TRUE 2.42957161
Upvotes: 1
Views: 42
Reputation: 79208
transform(myDat,xgt0=x > 0,x2= x^2)
x xgt0 x2
1 -0.5604756 FALSE 0.31413295
2 -0.2301775 FALSE 0.05298168
3 1.5587083 TRUE 2.42957161
Upvotes: 1
Reputation: 269556
Use within
like this:
set.seed(123)
myDat <- data.frame('x'=rnorm(3))
within(myDat, {
xgt0 <- x > 0
x2 <- x^2
})
giving:
x x2 xgt0
1 -0.5604756 0.31413295 FALSE
2 -0.2301775 0.05298168 FALSE
3 1.5587083 2.42957161 TRUE
Upvotes: 6