简体   繁体   English

我是 r 的新手。我试图通过使用 for 循环使我的代码不那么复杂

[英]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.

相关问题 我正在尝试在 R 中创建一个带有 while 循环的 Collat​​z 序列。我在这个 while 循环中做错了什么? - I am trying to create a Collatz sequence with while loop in R. What am i doing wrong in this while loop here? R。 我正在尝试将我的数据框子集几十年。 因此,我想通过使用列的值进行子集化 - R. I am trying to subset my data frame by decades. Therefore I want to subset by using values of a column R的新手。我正在尝试从mlbench软件包的Glass $ Fe中将0.00值添加.01。 - New to R. I am trying add .01 the 0.00 values in the Glass$Fe from the mlbench package 我正在尝试使用 R 获取矩阵中列的乘积。 我究竟做错了什么? - I'm trying to take the product of the columns in a matrix using R. What am I doing wrong? 我是 r 的新手。 如何将数据框变量值从数字转换为名称? 请参阅下面的代码 - I am new to r. How can I convert a data frame variable value from a number to a name? See code below 我在R中使用朴素贝叶斯(Naive Bayes)。 - I am using Naive Bayes in R. I have the titanic set, but predict() function produces error R中的快速傅立叶变换。我在做什么错? - Fast Fourier Transform in R. What am I doing wrong? 我正在尝试编写类似于for循环的while循环,我该如何在R中进行呢? - I am trying to write a while loop similar to my for loop.How should I go about it in R? R中的列计数。刚开始将其用于GWAS,我迷路了 - Column counting in R. Just started using it for GWAS and I am lost 我正在尝试在R中放置5个箱线图。它们每个都非常紧凑。 我该如何解决? - I am trying to to put 5 boxplot graphs in R. Each of them come out really squished. How do I fix this?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM