4

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?

2 Answers 2

6

Use the list argument of save():

save(list=substr(month,1,3), file="data.rda")
Sign up to request clarification or add additional context in comments.

Comments

5

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)
} 

4 Comments

This is a good solution. Let me try it out and see if anyone else comes up with a more direct solution.
This is a less flexible solution than baptiste's, because you've hard-coded the 3-letter month names. In general, code which allows arbitrary inputs to be processed, e.g. month <-'HitherePaulH';substr(month,8,4) :=)
I agree, but for the sake of illustration I thought this was fine.
there's month.abb to save typing and typos.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.