Basic R, how to populate a vector with results fro

2019-08-30 07:08发布

问题:

So I have a list of coordinates that I perform a chull on.

X <- matrix(stats::rnorm(100), ncol = 2)
hpts <- chull(X)

chull would return something like "[1] 1 3 44 16 43 9 31 41". I want to then multiple X by another vector to return only the values of X that are in the result set of chull. So for example [-2.1582511,-2.1761699,-0.5796294]*[1,0,1,...] = [-2.1582511,0,-0.5796294...] would be the result. I just don't know how to populate the second vector correctly.

Y <- matrix(0, ncol = 1,nrow=50)   #create a vector with nothing
# how do I fill vector y with a 1 or 0 based on the results from chull what do I do next?
X[,1] * Y  
X[,2] * Y

Thanks,

回答1:

To return only the values of X that are in the result set of hpts, use

> X[hpts]
## [1]  2.1186262  0.5038656 -0.4360200 -0.8511972 -2.6542077 -0.3451074  1.0771153
## [8]  2.2306497

I read it like "X such that hpts", or "the values of hpts that are in X"

Of course, these values of X are different from yours, due to my values of rnorm

To get a vector of 1s and 0s signifying results use

> Y <- ifelse(X[,1] %in% X[hpts], 1, 0)
> Y
## [1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 1 0 0
## [44] 0 1 0 0 1 0 1