[R] Why replacement has length zero? And How can I fix it?
soon yi
soon.yi at ymail.com
Sat Feb 2 21:57:41 CET 2013
Hi
for the loop section runif needs curved brackets
Try
IAP <-NA
for (i in 1:Sample.Size){
if (DataSet$SES[i]>0) {
IAP[i] <- ifelse(runif(1)>0.75, 1, 0) # High SES, higher chance to be in
Treatment #
}
else {
IAP[i] <- ifelse(runif(1)<=0.25, 1, 0) # Low SES, lower chance to be in
Treatment #
}
} # End loop #
IAP
IAP
zjiaqi19880219 wrote
> Hi, all,
>
> I am working on a project to run a simulation. I am now working on the
> main body of the simulation body, I generate the data and all work well
> before I identify a variable "IAP", there is always an error message as
> "replacement has length zero", and I do not know how to fix it. Can anyone
> help?
>
> Here is the code:
>
> library (mvtnorm)
>
> options(digits=2)
>
> # Set variable name #
> namelist1 <- c("Age", "Gender", "SES", "ISS", "IQTe", "PreTe")
>
> # Generate Data #
> Sample.Size <- 10 # Variable Sample Size #
> CorMat <- matrix(c(1.0 ,0.0 ,0.0 , 0.5, 0.2, 0.5,
> 0.0, 1.0 ,0.0, 0.0, 0.0, 0.0,
> 0.0 ,0.0 ,1.0, 0.5, 0.4, 0.5,
> 0.5, 0.0, 0.5, 1.0, 0.4, 0.7,
> 0.2, 0.0, 0.4, 0.4, 1.0, 0.9,
> 0.5, 0.0, 0.5, 0.7, 0.9, 1.0),ncol=6) # Correlation Matrix #
>
> DataSet <- rmvnorm(Sample.Size, mean=c(0,0,0,0,0,0), sigma=CorMat) # Draw
> Sample.Size covariate set all mean 0 #
> DataSet <- as.data.frame(DataSet)
> names(DataSet) <- namelist1
> DataSet
>
> # For Treatment IAP #
> IAP <- matrix(0, nrow=Sample.Size)
> for (i in 1:Sample.Size){
> IAP[i] <- if (DataSet$SES>0)
> {
> ifelse(runif[1]>0.75, 1, 0) # High SES, higher chance to be in Treatment
> #
> }
> IAP[i] <- if (DataSet$SES<=0)
> {
> ifelse(runif[1]<=0.25, 1, 0) # Low SES, lower chance to be in Treatment
> #
> }
> } # End loop #
> IAP
>
> Error in IAP[i] <- if (DataSet$SES > 0) { : replacement has length zero
> In addition: Warning message:
> In if (DataSet$SES > 0) { :
> the condition has length > 1 and only the first element will be used
>
> Thanks!
--
View this message in context: http://r.789695.n4.nabble.com/Why-replacement-has-length-zero-And-How-can-I-fix-it-tp4657373p4657380.html
Sent from the R help mailing list archive at Nabble.com.
More information about the R-help
mailing list