基本 R,如何使用函数的结果填充向量 [英] Basic R, how to populate a vector with results from a function

查看:32
本文介绍了基本 R,如何使用函数的结果填充向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个坐标列表,我可以在上面执行一个chull.

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

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

chull 会返回类似[1] 1 3 44 16 43 9 31 41"的内容.然后我想用另一个向量乘以多个 X 以仅返回 chull 结果集中的 X 值.因此,例如 [-2.1582511,-2.1761699,-0.5796294]*[1,0,1,...] = [-2.1582511,0,-0.5796294...] 将是结果.我只是不知道如何正确填充第二个向量.

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

谢谢,

推荐答案

要只返回hpts结果集中的X值,使用>

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

我读起来像是X 使得 hpts",或X 中的 hpts 的值"

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

当然,这些X的值和你的不一样,因为我的rnorm

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

要获得表示结果的 1 和 0 向量,请使用

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

这篇关于基本 R,如何使用函数的结果填充向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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