[英]I am new to r. I am trying to make my code less complicated by using a for loop
Here is my current code... can I make this a for loop?这是我当前的代码...我可以将其设为 for 循环吗?
#sample1, sample2, …, sample6 where samplei is sampling 10^(ith)
sample1 <- abs(rnorm(10)) #use abs because bellcurve is + and -
sample2 <- abs(rnorm(10^2))
sample3 <- abs(rnorm(10^3))
sample <- abs(rnorm(10^4))
sample5 <- abs(rnorm(10^5))
sample6 <- abs(rnorm(10^6))
R is really good at vectorization, which means that almost any time you're trying to use a for loop, there's a better/faster way to do it. R 非常擅长矢量化,这意味着几乎任何时候您尝试使用 for 循环,都有更好/更快的方法来实现。 I would rewrite your sample as:
我会将您的示例重写为:
samples <- abs(rnorm(10^seq(6)))
Then each sample can be accessed as samples[1]
etc.然后每个样本都可以作为
samples[1]
等访问。
If you also want to assign it to 6 different variables you will need to do:如果您还想将其分配给 6 个不同的变量,您需要执行以下操作:
n = 6
invisible(sapply(1:n, function(i) assign(x = paste("sample", i, sep = ""),
value = abs(rnorm(10^i)),
envir = .GlobalEnv)))
Or with a for loop:或者使用 for 循环:
for(i in 1:n)
{
assign(x = paste("sample", i, sep = ""), value = abs(rnorm(10^i)), envir = .GlobalEnv)
}
But it makes much more sense to store it as a list, like in:但将其存储为列表更有意义,例如:
samples = lapply(1:6, function(i) abs(rnorm(10^i)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.