Valy
Valy

Reputation: 444

How Can I Copy/Paste All Environment Variables in RStudio?

I generated many variables as part of a project, and I am finding that I will be needing to re-combine them in a list (ex: list(var1, var2, ..., varn). Is there a way to plug them in without typing up each one?

Upvotes: 1

Views: 871

Answers (3)

jpdugo17
jpdugo17

Reputation: 7116

library(tidyverse)

var1 <- 'a'
var2 <- 4
var3 <- head(iris)

#Searching all names that start with var

nms <- str_subset(names(.GlobalEnv), '^var')

(vars <- map(nms, ~eval(parse(text = .))) %>%
  set_names(nms))
#> $var1
#> [1] "a"
#> 
#> $var2
#> [1] 4
#> 
#> $var3
#>   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#> 1          5.1         3.5          1.4         0.2  setosa
#> 2          4.9         3.0          1.4         0.2  setosa
#> 3          4.7         3.2          1.3         0.2  setosa
#> 4          4.6         3.1          1.5         0.2  setosa
#> 5          5.0         3.6          1.4         0.2  setosa
#> 6          5.4         3.9          1.7         0.4  setosa

#alternative we can call enframe on the resulting list.

enframe(vars)
#> # A tibble: 3 × 2
#>   name  value       
#>   <chr> <list>      
#> 1 var1  <chr [1]>   
#> 2 var2  <dbl [1]>   
#> 3 var3  <df [6 × 5]>

Created on 2021-12-25 by the reprex package (v2.0.1)

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 389325

What @Roland mentioned -

var1 <- 1:5
var2 <- 1:10
data <- mget(paste0('var', 1:2))
data

#$var1
#[1] 1 2 3 4 5

#$var2
# [1]  1  2  3  4  5  6  7  8  9 10

Also, with ls and pattern -

data <- mget(ls(pattern = 'var'))

Upvotes: 1

el_pazzu
el_pazzu

Reputation: 416

You can always generate a list from an enviroment (list2env) and the inverse too (as.list):

L <- list(a = 1, b = 2:4, p = pi, ff = gl(3, 4, labels = LETTERS[1:3]))
e <- list2env(L)
e$ff
# [1] A A A A B B B B C C C C
#Levels: A B C

as.list(e)
#$ff
# [1] A A A A B B B B C C C C
#Levels: A B C
#
#$p
#[1] 3.141593
#
#$b

Upvotes: 1

Related Questions