两个向量与二进制 (0/1) 结果的逻辑比较 [英] Logical comparison of two vectors with binary (0/1) result

查看:26
本文介绍了两个向量与二进制 (0/1) 结果的逻辑比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于一个任务,我必须创建一个随机向量 theta,一个包含 theta 中每个元素相关概率的向量 p,以及另一个随机向量 u.到目前为止没有问题,但我坚持我在下面报告的下一条指令:

For an assignment I had to create a random vector theta, a vector p containing for each element of theta the associated probability, and another random vector u. No problems thus far, but I'm stuck with the next instruction which I report below:

生成一个向量 r1,如果 pi ≥ ui,则在位置 i 上为 1,如果 pi <则为 0.你好这向量 r1 是给定潜在变量 theta 的 Rasch 项.

Generate a vector r1 that has a 1 in position i if pi ≥ ui and 0 if pi < ui. The vector r1 is a Rasch item given the latent variable theta.

theta=rnorm(1000,0,1)
p=(exp(theta-1))/(1+exp(theta-1))
u=runif(1000,0,1)

我尝试了以下代码,但不起作用.

I tried the following code, but it doesn't work.

r1<-for(i in 1:1000){
if(p[i]<u[i]){
  return("0")
} else {
  return("1")}
}

推荐答案

您可以使用 ifelse 函数:

r1 <- ifelse(p >= u, 1, 0)

或者您可以简单地将逻辑比较转换为数值向量,从而将 TRUE 变为 1,将 FALSE 变为 0:

Or you can simply convert the logical comparison into a numeric vector, which turns TRUE into 1 and FALSE into 0:

r1 <- as.numeric(p >= u)

这篇关于两个向量与二进制 (0/1) 结果的逻辑比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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