0

I am trying to write the following loop over an empirical data set where each ID replicate has a different number of observations for each sample period. Any suggestions would be greatly appreciated!

a <- unique(bma$ID)
t <- unique(bma$Sample.period)

# empty list to hold the data

dens.data <- vector(mode='list', length = length(a) * length(t))
tank1 <- double(length(a))
index = 0
for (i in 1:length(a)){
  for (j in 1:length(t)){
    index = index + 1
    tank1[index] = a[index] ### building an ID column
    temp.tank <- subset(bma, bma$ID == a[i])
    time.tank <- subset(temp.tank, temp.tank$Sample.period == t[j])
    temp1 <- unique(temp.tank$Sample.period)
    temp.tank <- data.frame(temp.tank, temp1)
    dens.1 <- density(time.tank$Biomass_.adults_mgC.mm.3, na.rm = T)
    # extract the y-values from the pdf function - these need to be separated by each Replicate and Sample Period
    dens.data[[index]] <- dens.1$y
  }
}

#### extract the data and place into a dataframe

dens.new<- data.frame(dens.data)
dens.new
colnames(dens.new) <- c("Treatment","Sample Period","pdf/density for biomass")
all<- list(dens.new)
all

### create new spreadsheet with all the data from the loop

dens.new.data<- write.csv(dens.new, "New.density.csv")  ## export file to excel spreadsheet

Calling dens.new<- data.frame(dens.data) Yield the following error message:

Error in data.frame(c(...)  : 
  arguments imply differing number of rows: 512, 0

The loop seems to work for dens.data[[1]] but returns NULL for dens.data[[>1]]

r2evans
  • 141,215
  • 6
  • 77
  • 149
m_west
  • 1
  • 2
  • Can you make this question [minimal and reproducible](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) by including a small dataset and expected results? – shayaa Oct 11 '16 at 21:39

1 Answers1

0

As there isn't a minimal example, it is difficult for me to guess what the original data.frame looks like. However, as for the error message, it is clear that your for-loop fails to assign values to the list dens.data for indices greater than 1.

My guess is that the index didn't update by index = index + 1. Maybe you could try changing the equal sign = to the standard R assignment operator <- and see whether the whole list is updated.

I heard that using equal sign for assignment may cause some problems in an older version of R, but I'm not sure whether you are facing the same problem. Anyway, using <- to assign a value is always safer and recommended.

Junnan
  • 161
  • 1
  • 4