Soumendra
Soumendra

Reputation: 1202

Using a parameter as a variable name inside a function in R

I am trying to incorporate the name of the month in the name of the variable being stored.

import <- function(month) {
  dataobj <- letters
  assign("x", dataobj)
  save("x", file="data.rda")
}

works. But the following doesn't work -

import <- function(month) {
  dataobj <- letters
  assign(substr(month, 1, 3), dataobj)
  save(substr(month, 1, 3), file="data.rda")
}

It seems that save() will accept "x" but not substr(month, 1, 3).

Any ideas how to fix this?

Upvotes: 4

Views: 1147

Answers (2)

baptiste
baptiste

Reputation: 77116

Use the list argument of save():

save(list=substr(month,1,3), file="data.rda")

Upvotes: 6

Paul Hiemstra
Paul Hiemstra

Reputation: 60984

In stead of creating objects in the environment with a specific, month dependent, name, I would use a list of objects where month is used as name.

dat = lapply(1:4, function(x) letters)
names(dat) = c("Jan","Feb","Mar","Apr")
> dat
$Jan
 [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" 
[20] "t" "u" "v" "w" "x" "y" "z"                                                 

$Feb                                                                             
 [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" 
[20] "t" "u" "v" "w" "x" "y" "z"                                                 

$Mar                                                                             
 [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" 
[20] "t" "u" "v" "w" "x" "y" "z"                                                 

$Apr                                                                             
 [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" 
[20] "t" "u" "v" "w" "x" "y" "z"  

Saving this list can be done easily using save(dat). If you are keen on saving the months in separate objects:

lapply(names(dat), function(month) {
  save(dat[[month]], file = sprintf("%s.rda", month)
 })

or using the good old for loop:

for(month in names(dat)) {
  save(dat[[month]], file = sprintf("%s.rda", month)
} 

Upvotes: 5

Related Questions