[英]How to replace all negative values in vector by 0 in R
I have a randomly generated vector from a normal distribution with 50 elements 我有一个随机生成的矢量,来自正态分布,有50个元素
vector<-c(rnorm(50))
I want to change all negative values to 0 and positive values to 1 我想将所有负值更改为0,将正值更改为1
I used this function and indexing however then I do not get vector with 50 elements 我使用了这个函数和索引但是我没有得到50个元素的向量
vector[ vector< 0 ] <- 1
vector[ vector> 0 ] <- 0
How should I proceed? 我该怎么办?
Generate some data 生成一些数据
x = rnorm(50)
then either 那么
x = ifelse(x > 0, 1, 0)
or 要么
x[x < 0] = 0
x[x > 0] = 1
Or even better 甚至更好
as.numeric (x>0)
However since the standard normal is symmetric about 0, why not simulate directly via 然而,由于标准法线对称约为0,为什么不直接模拟通过
sample(0:1, 50, replace=TRUE)
The problem is that in the first query you replace all value smaller 0 by values larger zero so the trick is to switch 问题是在第一个查询中,您将所有值小0替换为大于零的值,因此诀窍是切换
vector[ vector< 0 ] <- 1
vector[ vector> 0 ] <- 0
into 成
vector[ vector> 0 ] <- 0
vector[ vector< 0 ] <- 1
Note that you are also slightly biased towards 0 but that should only be marginal 请注意,您也略微偏向0,但这应该只是边际
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.