在应用于向量的函数中使用带有随机变量生成的 ifelse [英] Using ifelse with random variate generation in a function applied to a vector

查看:35
本文介绍了在应用于向量的函数中使用带有随机变量生成的 ifelse的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个函数,该函数根据其输入生成一个随机数并将其应用于布尔向量.此函数将用于生成包含约 5 亿个元素的测试数据.

I want to create a function that generates a random number based on its input and apply it to a boolean vector. This function will be used to generate test data with approx 500M elements.

f <- function(x, p) ifelse(x, runif(1)^p, runif(1)^(1/p))
f(c(T,T,T,F,F,F), 2)   

我得到的不是我想要的.

What I get is not what I wanted.

[1] 0.0054 0.0054 0.0054 0.8278 0.8278 0.8278

我希望输入向量的每个元素都有一个新的随机数,而不是两个重复的随机数.为什么我会得到这个结果,我怎样才能得到与

I'd expect a new random number for every element of my input vector, not two random numbers repeated. Why do I get this result, and how can I get the desired result which would be the same as

c(runif(3)^2, runif(3)^(1/2))

为每个元素产生一个新的随机数

which yields a new random number for every element

0.0774 0.7071 0.2184 0.8719 0.9990 0.8819

推荐答案

您需要制作两个不同的随机数向量,其长度与 x-vector 的长度相同.

You would need to make two different vectors of random numbers of the same length as the x-vector.

 f <- function(x, p) ifelse(x, runif(6)^p, runif(6)^(1/p))
 f(c(T,T,T,F,F,F), 2)   
 [1] 0.3040201 0.5543376 0.7291466 0.5205014 0.3563542 0.8697398

或更一般地说:

f <- function(x, p) ifelse(x, runif( length(x) )^p, runif( length(x) )^(1/p))

ifelse 函数并没有真正进行循环.第二个和第三个参数各计算一次.

The ifelse-function is not really doing looping. The second and third arguments get evaluated once each.

这篇关于在应用于向量的函数中使用带有随机变量生成的 ifelse的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆