0

I wrote a loop generating the average and standard deviation of the randomized data set. The randomization size would differ depending on the sample size of each sample. Here I have sample sizes 80, 50, 32, and 20, so I wrote a loop as below.

However, I kept receive the error "Error in CT.raw$average[i, ] <- mean(as.numeric(unlist(as.data.frame(CT.raw[i, : incorrect number of subscripts on matrix"

The tricky thing is, I chose some numbers and plug in as i, the mean and standard deviation would work out fine. I have tried many times but have not yet figured it out where I have been doing wrong.

The sample raw data set is as the link below:

https://rit0-my.sharepoint.com/:f:/g/personal/jc3992_ad_rit_edu/Ev4WZAETEg9OkT3u0esOS2cBq6Z8qTf8XkthdfGNA7VoBA?e=RkVFRA

    random.f <- function(Data){
  x=seq(from=2, to=1730, length=1729)
  Data=CT.raw
  set.seed(123)
  for (i in x){
  #for j = 11 to 91
  if (is.na(CT.raw[i,90])==FALSE)
  {
    index = sample(1:80, 35, replace=FALSE)
    index <- as.numeric(index)
    CT.raw <- as.data.frame(CT.raw)
  CT.raw$average[i,]= mean(as.numeric(unlist(as.data.frame(CT.raw[i,11:90])[c(index),])), trim = 0, na.rm = TRUE) 
  }else if(is.na(CT.raw[i,60])==FALSE & is.na(CT.raw[i,61])==TRUE)
    {
    index = sample(1:50, 25, replace=FALSE)
    index <- as.numeric(index)
  CT.raw$average[i,]= mean(as.numeric(unlist(as.data.frame(CT.raw[i, 11:90])[c(index),])), trim=0, na.rm=TRUE) 
  }else if(is.na(CT.raw[i,42])==FALSE & is.na(CT.raw[i,43])==TRUE)
    {
    index = sample(1:32, 20, replace=FALSE)
    index <- as.numeric(index)
  CT.raw$average[i,]= mean(as.numeric(unlist(as.data.frame(CT.raw[i,11:90])[c(index),])), trim=0, na.rm=TRUE)
  }else (is.na(CT.raw[i,30])==FALSE & is.na(CT.raw[i,31])==TRUE)
    {
    index = sample(1:20, 15, replace=FALSE)
    index <- as.numeric(index)
  CT.raw$average[i,]= mean(as.numeric(unlist(as.data.frame(CT.raw[i,11:90])[c(index),])), trim=0, na.rm=TRUE)
  }
  }
}

Chen
  • 383
  • 2
  • 12
  • It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. Providing sample data on an external site rather than in the question itself is not as helpful. I'm not sure what this function does because despite the fact that you pass in `Data`, you seem to reassign right away to `CT.raw` and then never return anything from the function. – MrFlick May 17 '19 at 18:21
  • like @MrFlick said you write `Data=CT.raw` when it would make more sense if it were `CT.raw=Data` – MDEWITT May 17 '19 at 19:07
  • I see. I will try that and let you know if it works. Thank you very much! earlier I did not understand the first comment meant. – Chen May 18 '19 at 16:32

0 Answers0