-1

so, I'm a noobie in R and want to make my experience with it as straightforward as possible. I work with multi-response datasets (like 50+ responses) and would like to avoid manually typing in x1 = dataset$x1 / x2 = dataset$x2 / ect....

Is there a script to make every column header an object?

Cheers!

  • Have a look at `attach()` and `detach()`. – ricoderks Dec 11 '19 at 15:30
  • Please can you provide a reproductible exemple of what you did and, if possible, a piece of what you expect ? For example you can use mtcars dataset. Have you used `split()` function for ex ? – Paul Dec 11 '19 at 15:45
  • 1
    It would be probably better to not create a bunch of loose variables in your global environment. If you don't like typing `dataset$` all the time, you can use functions like `with()` to avoid the repetition or use packages like `dplyr` which make it even easier to work with column names. I would **not** suggest `attach()`. That can really mess up your global environment. Why do you need all these separate variables? What you trying to do? It would help to share some sort of [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). – MrFlick Dec 11 '19 at 15:47
  • 1
    I want to emphasize MrFlick's points. **Don't use `attach`.** Typing `dataset$` a bunch sucks, don't do that either. Use `dplyr` or `data.table`, make sure you're using `data` arguments in functions that have them, and use `with` on functions that don't. [See here for a little more on why attach is bad](https://stackoverflow.com/q/10067680/903061). – Gregor Thomas Dec 11 '19 at 16:04

2 Answers2

0

There are two common approaches (these have also been mentioned in the comments):

  1. You could attach() the dataset, and detach() when done.
  2. You could also use with().

Suppose you have a data.frame named dataset, and in it are $x1 and $x2.
An example using attach() would be:

attach(dataset)
newvar  <- x1 + x2
newvar2 <- x1 - x2
detach(dataset)

And an example using with():

with(dataset, {
  newvar  <- x1 + x2
  newvar2 <- x1 - x2
})

I hope I answered your question, if not, feel free to rephrase / edit.

For further examples, take a look at the example in ?attach(), and the boxplot example in ?with().

bert
  • 332
  • 1
  • 9
0

Here is a reproducible suggestion using only base R functions:

# mtcars is dummy dataset to work with
list_objects = as.list(mtcars) # make a list with all your columns

# note that you can do lapply(list_object, function) at this stage...

#but if you really want your objects to be in your global environment here is the trick :

list2env(list_objects, globalenv()) # extract the objects of the previous list in your environment 
Paul
  • 2,850
  • 1
  • 12
  • 37