简体   繁体   English

使用if-else的R中的For-Loop:如何保存输出

[英]For-Loop in R with if-else: How to save the output

I am trying to save the output of the code below. 我想保存下面代码的输出。 I know "print" is the problem, but I do not know what works instead. 我知道“打印”是问题,但我不知道是什么有用。

I generally wonder if there is not another way instead of the for-loop: For each value in the vector (x), I want to draw a new random number (here with runif) and match it to a given value (here for example 0.5). 我通常想知道是否没有其他方式而不是for-loop:对于向量(x)中的每个值,我想绘制一个新的随机数(这里使用runif)并将其与给定值匹配(这里例如0.5)。 Depending on the result, a new value for x should be stored in a vector x2 (similar to the if-else example below). 根据结果​​,x的新值应存储在向量x2中(类似于下面的if-else示例)。 Waiving the for-loop, I could not find a way to always draw a new random number for each value in vector x. 放弃for循环,我找不到总是为向量x中的每个值绘制一个新的随机数的方法。 I would be very grateful for any help! 我会非常感谢任何帮助!

x <- c(2,2,2,3,3,3)

for(i in x){
  if(runif(1) <= 0.5){
    print(i + 1)
  } else {
    print(i)
  }
}

Or you could use lapply , then you don't have to modify an object outside your loop each step. 或者您可以使用lapply ,然后您不必在每个步骤中修改循环外的对象。

x <- c(2,2,2,3,3,3)

x2 <- unlist(lapply(x, function(x){
          if(runif(1) <= 0.5) return(x +1)
          return(x)
}))

x2

Try this code: 试试这段代码:

x <- c(2,2,2,3,3,3)
x2<-NULL

for(i in 1:length(x)){
   if(runif(1) <= 0.5){
     x2[i]<-1
   } else {
     x2[i]<-2
   }
 }

Your output 你的输出

x2
[1] 1 2 2 1 2 1

In x2 you have random numbers with given values (1 and 2) related to the runif probability. x2您具有与runif概率相关的给定值(1和2)的随机数。

This is the same thing in a single row: 这一行在同一行中是相同的:

ifelse(runif(n = length(x))<=0.5,1,2)
[1] 1 2 2 2 1 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM