Question

I want to smash a data.frame/tibble in R

  • 19 May 2022
  • 3 replies
  • 88 views

Userlevel 3
Badge +1

Hey,

So in R I have a tibble that is 1 x 9 and what I want to do is basically take those 9 variables and move them out of the tibble and become their own, free, variables.

Aka I want to turn something like:

df <- tibble::tibble(a = 1, b = 2, c = 3)

into

a <- 1
b <- 2
c <- 3

Without having to either individual put each variable into a new one with

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

Things I have tried:

tibble::deframe(df)
unlist(df)

Is there like a single function somewhere that can do this or do I have to faff about?


3 replies

Userlevel 3
Badge +1

You can use a loop:

 

#empty list
list <- list()

#each column is an object in the list
for(i in 1:ncol(df)) {
list[[i]] <- df[ , i]
}

#rename based on column names
names(list) <- names(df)

#export to environment if needed
list2env(list, .GlobalEnv)

 

Userlevel 3
Badge +1

Thanks so much @Magdalena Nowakowska 
So interestingly when I run that each variable comes back as a tibble rather than a vector:
 

> df <- tibble::tibble(a = 1, b = 2, c = 3)
> #each column is an object in the list
> for(i in 1:ncol(df)) {
+ list[[i]] <- df[ , i]
+ }
> #rename based on column names
> names(list) <- names(df)
> #export to environment if needed
> list2env(list, .GlobalEnv)
<environment: R_GlobalEnv>
> str(a)
tibble [1 × 1] (S3: tbl_df/tbl/data.frame)
$ a: num 1
>

I thought maybe someone, somewhere might have written a function that basically did 

smash(df)

 

Userlevel 3
Badge +1

as.list rather than unlist or new list assignment works for me for the above example

list2env(as.list(df), envir = globalenv())

 

Reply