0

This is related to a previous question:

Basic R, how to populate a vector with results from a function

But I thought I would post a new one because I have an additional requirement. Take this R code.

X <- matrix(stats::rnorm(100), ncol = 2)
hpts <- chull(X)
Y <- ifelse(X[,1] %in% X[hpts], 1, 0)
c(X,Y)
Z <- matrix(0,ncol = 1,nrow =50)

I want to add in an additional vector Z preserving the order of hpts. So if t(t(hpts)) looks like this:

[1,]   48
[2,]   27
[3,]   15
[4,]   13
[5,]   39
[6,]    2
[7,]    5
[8,]   50

then I want the 48th row Z to have 1, the 27th row to have 2, the 15th row to have 3 etc.etc. I have attempted to do this with a for loop:: for (i in Y) {...} but I have not had success. Any pointers would be appreciated.

Community
  • 1
  • 1
KrisErickson
  • 73
  • 1
  • 10

1 Answers1

2

This should do it:

Z[c(hpts),1] <- seq_along(hpts)
BrodieG
  • 51,669
  • 9
  • 93
  • 146
  • @KrisErickson, it's called a replacement. See the documentation for `[` for more details. Basically, you can index the portion of a vector/matrix you want to replace, and then fit in a vector of (typically) the same size there. – BrodieG Feb 28 '14 at 14:16