I have a data set which has over 100 variables/column headers and I want to load all of them as variables into R. I can load the dataset in fine, but I find it tedious having to convert each column as
var1 <- df$col1
var2 <- df$col2 . . .
all the way to var100 <- df$col100. How can I quickly make all of these columns turn into variables?
Bonus points for saying how to only get certain columns turn into variables quickly, such as columns 5 through 85.
I know I should also post a usable data frame or something for a person answering to download and manipulate but I don't know how to get my dataframe in R into my StackOverflow question so I only have an example 5x5 grid image of the data in excel to provide. Again this is a far larger dataset than the image shows.
CodePudding user response:
You could also do it with assign()
:
dat <- data.frame(
var1 = rnorm(10),
var2 = rnorm(10),
var3 = rnorm(10),
var4 = rnorm(10),
var5 = rnorm(10)
)
for(i in 1:ncol(dat)){
assign(paste0("var", i), dat[[paste0("var", i)]])
}
var1
#> [1] -0.98086606 0.40048599 1.19099096 1.03191817 -1.06956025 -0.03919399
#> [7] 1.32809944 1.05396682 0.07826412 1.00137558
var2
#> [1] -0.37338283 0.48710182 0.80729920 0.98664978 0.06286747 2.77966983
#> [7] -0.08503804 -0.17249172 0.88482571 -0.83201587
Created on 2022-06-03 by the reprex package (v2.0.1)
This also makes it easy to only do some columns by changing the numbers over which the loop operates (e.g., 1:ncol(dat)
could be something like c(1,3,7,12)
or 5:85
).