6

我正在做一个项目,我必须做很多重复,如果我可以在 for 循环中处理多个对象,生活会容易得多。为了阐明我的问题,我想出了一个(愚蠢的)例子

例如,如果这样做是为了创建我的数据:

for (i in 1:10)
  {
assign(paste("Season",i, sep = ""),rnorm(10,0,1))
}

所以我有第 1 季、第 2 季、..、第 10 季。是否可以使用 for 循环将 10 个对象的第一个数字更改为零。半伪代码看起来像这样。但这当然行不通。

for (i in 1:10)
  {
Seasoni[1]<-0
}

有人有解决方案吗?

斯特凡

4

2 回答 2

18

您问题的直接解决方案是使用getwithpaste

for(i in 1:10)  
{
    Object = get(paste0("Season", i))
    Object[1] = 0
    assign(paste0("Season", i), Object)
}

但不要这样做

这是对 R 的可怕使用。正如评论中所建议的,将结果存储在列表中:

Seasons = lapply(rep(10,10), rnorm) #Generate data
Seasons

然后应用函数:

Seasons = lapply(Seasons, replace, list=1, values=0)
于 2013-10-08T18:35:25.753 回答
2

这是基于@joran 评论的解决方案

> set.seed(1) # for reproducibility
> # the following does the same as your `for` loop and returned value is a list
> Season.list <- replicate(10, rnorm(10, 0, 1), simplify=FALSE) 
> # giving some names
> names(Season.list) <- paste0("Season", 1:length(Season.list))
> # setting first element to 1    
> Season.list <- lapply(Season.list, function(x) {x[1] <- 0; x})
> list2env(Season.list, envir = .GlobalEnv) # will give you each `Season` as you  want :D

另外,另一种方法,

> set.seed(1)
> Season <- replicate(10, rnorm(10, 0, 1))  # the returned object is a matrix
> colnames(Season) <- paste0("Season", 1:ncol(Season))
> Season[1,] <- 0  

如果您想为每个向量提供一个向量,请Season使用attach(不是一个好主意)

> attach(as.data.frame(Season))
> Season1
 [1]  0.0000000  0.1836433 -0.8356286  1.5952808  0.3295078 -0.8204684  0.4874291  0.7383247  0.5757814 -0.3053884
> Season2
 [1]  0.00000000  0.38984324 -0.62124058 -2.21469989  1.12493092 -0.04493361 -0.01619026  0.94383621  0.82122120
[10]  0.59390132
于 2013-10-08T18:38:46.287 回答