Assigning a sample to a variable - Need help with code interpretation

Hi, I need help to interpret the following code.

I understand that I'm assigning a sample with binary values with replacement and probability of the value being 0 of 90% and 1 of 10%. What I don't understand is the first part:

test[disease==0] <- sample(c(0,1)...

Usually square brackets would be to indicate the index e.g., 'test[1]', but in this context, I just don't understand what is happening with a conditional in square brackets. Can anyone assist?

Please, see more of the context in the following code:

set.seed(1, sample.kind = "Rounding") 
disease <- sample(c(0,1), size=1e6, replace=TRUE, prob=c(0.98,0.02))
test <- rep(NA, 1e6)
test[disease==0] <- sample(c(0,1), size=sum(disease==0), replace=TRUE, prob=c(0.90,0.10))
test[disease==1] <- sample(c(0,1), size=sum(disease==1), replace=TRUE, prob=c(0.15, 0.85))

Its about where the results of the sample go to. I.e a subset of test that meets the condition are the ones that (recieve the sample results)

Can you expand on that? What is happening here? Is 'disease' nested in 'test'?

If you can suggest how to look for it on Google (key words) that could also help.

disease and test are separate vectors neither inside the other however they are the same length, so the author presumably intents to utilise a natural alignment. The key to understanding what is happening in your example is to think about the general computer science concept of indexing into (an array). square brackets in R are used to index into a vector
Here is some illustrative code that I hope will help you

# setup
(sqrs <- (1:3)^2)
(l <- letters[1:3])

#direct use 
sqrs[1]
l[1]

#indirect use 
number <- 1
sqrs[number]
l[number]

# again with logicals (what to include what to not) rather than the numbers of what to include
(tf <- c(TRUE,FALSE,TRUE))
sqrs[tf]
l[tf]
2 Likes

Thank you @nirgrahamuk, that was very useful!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.