在R中函数内使用参数作为变量名

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)

有什么办法可以解决这个问题吗?

2个回答

6
使用save()方法的list参数:
save(list=substr(month,1,3), file="data.rda")

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

这是一个不错的解决方案。让我试一下,看看是否有人能提出更直接的解决方案。 - Soumendra
1
这是比Baptiste的解决方案不够灵活,因为你已经硬编码了3个字母的月份名称。通常,代码应该允许处理任意输入,例如 month <-'HitherePaulH';substr(month,8,4) :=)。 - Carl Witthoft
我同意,但是为了举例说明,我认为这样很好。 - Paul Hiemstra
1
month.abb可以节省打字和减少拼写错误。 - baptiste

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接