4

我正在尝试将月份的名称合并到正在存储的变量的名称中。

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

作品。但以下不起作用 -

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

似乎save()将接受"x"但不接受substr(month, 1, 3)

任何想法如何解决这一问题?

4

2 回答 2

6

使用 的list参数save()

save(list=substr(month,1,3), file="data.rda")
于 2012-05-07T09:09:09.647 回答
5

我不会在环境中创建具有特定的、依赖于月份的名称的对象,month而是使用用作名称的对象列表。

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"  

保存此列表可以使用save(dat). 如果您热衷于将月份保存在单独的对象中:

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

或使用旧的 for 循环:

for(month in names(dat)) {
  save(dat[[month]], file = sprintf("%s.rda", month)
} 
于 2012-05-07T08:14:15.970 回答