mercredi 23 septembre 2020

Looping over a set of number generating commands in R

Below, I'm showing a block of code to generate some set of item scores in R. However, there seems to be a fair amount of unnecessary repetition to get to the final data.

I was wondering if there might be a more compact way of achieving the same data in R?

set.seed(8649)     
N      = 10        
latent = rnorm(N)  

##### generate latent responses to items
item1 = latent + rnorm(N, mean=0, sd=0.2)  
item2 = latent + rnorm(N, mean=0, sd=0.3)
item3 = latent + rnorm(N, mean=0, sd=0.5)
item4 = latent + rnorm(N, mean=0, sd=1.0)
item5 = latent + rnorm(N, mean=0, sd=1.2)  

##### convert latent responses to ordered categories
item1 = findInterval(item1, vec=c(-Inf,-2.5,-1, 1,2.5,Inf)) 
item2 = findInterval(item2, vec=c(-Inf,-2.5,-1, 1,2.5,Inf))
item3 = findInterval(item3, vec=c(-Inf,-3,  -2, 2,3,  Inf))  
item4 = findInterval(item4, vec=c(-Inf,-3,  -2, 2,3,  Inf))
item5 = findInterval(item5, vec=c(-Inf,-3.5,-3,-1,0.5,Inf))

data = cbind(item1, item2, item3, item4, item5)



Aucun commentaire:

Enregistrer un commentaire