我正在开发一个项目,我必须做很多重复,如果我可以在for循环中处理多个对象,那么生活会更容易。为了解释我的问题,我提出了一个(愚蠢的)例子
例如,如果这样做是为了创建我的数据:
for (i in 1:10)
{
assign(paste("Season",i, sep = ""),rnorm(10,0,1))
}
所以我有Season1,Season2,..,Season10。 是否可以使用for循环将10个对象的第一个数字更改为零。半伪代码看起来像这样。但当然这不起作用。
for (i in 1:10)
{
Seasoni[1]<-0
}
有解决方案的人吗?
的Stefan
答案 0 :(得分:10)
您问题的直接解决方案是将get
与paste
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)
答案 1 :(得分:1)
这是基于@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