Home > database >  How to automatically transform columns into objects in R?
How to automatically transform columns into objects in R?

Time:02-14

I need that each column of my dataset become an object named with that column's name and containing its values as the object value.

I know how to do the process manually (see "Process question" heading below), but I need to automatize and generalize the process with as few rows as possible.

Example data
library(tibble)
df <- tibble(a = 1, b = 2, c = 3, d = 4)
Input
> df
# A tibble: 1 x 4
      a     b     c     d
  <dbl> <dbl> <dbl> <dbl>
1     1     2     3     4
    

Process Question

How to automatize this part?

a <- df$a
b <- df$b
c <- df$c
d <- df$d

Output

> a;b;c;d
[1] 1
[1] 2
[1] 3
[1] 4

CodePudding user response:

tibble/data.frame are list. So, we can use list2env (or use attach)

list2env(df, .GlobalEnv)

-checking

> a
[1] 1
> b
[1] 2
  • Related