0

I have some dataframe, bonusdataframe3, where I want divide every 200 rows by a different value. For example, when I run the code:

 bonusdf<-reactive({
    req(bonusdataframe3())
    bonuscc0<-data.frame(hours=c(), conc=c())
    

    for(n in 1:nrow(iondat())-4){
      
       dxframe<-data.frame(hours=out()[[1]], conc=(bonusdataframe3()$conc[(n-1)*201:n*201]))/unlist(cindat()[2,n+6:nrow(iondat())]))


      bonuscc0<-rbind(bonuscc0, dxframe)

     }
    bonuscc0
  })

I get the error

Warning: Error in data.frame: arguments imply differing number of rows: 201, 0

Which is really strange to me because the code

bonusdf<-reactiveValues()

   bonusdf2<-reactive({
    req(bonusdataframe3())

    bonusdf<-bonusdataframe3()
    bonusdf$conc<-bonusdataframe3()$conc[0:201]/unlist(cindat()[2,6])
    bonusdf
  })

Gives me what I want. bonusdataframe3()$conc[0:201] gives me the first 200 entries and I can divide them by unlist(cindat()[2,6]). nrow(iondat()-4) gives me the values I want, in this case it's just 1, so the for loop is going from 1:1 which should just iterate over one, once.

Does anyone know where I am going wrong here? Why is my loop empty?

David_Cola
  • 21
  • 5
  • 2
    Various problems here: First, R arrays are base 1, so conc[0:201] is the same as conc[1:201] and returns 201 elements, not 200. Second: the colon operator takes precedence over multiplication, so `conc[(n-1)*201:n*201])` should be `conc[((n-1)*201):(n*201)])` (however take into account the first point). – Ric Dec 01 '22 at 15:11
  • 3
    A `for` loop might be feasible (and certainly a "CS" way to look at it), but it is hugely inefficient in R. A better way would be to use a grouping function (e.g., `split` and/or `\`split<-\``, or `dplyr::group_by`). – r2evans Dec 01 '22 at 15:11
  • 1
    Add a column to your data grouping every 200 rows `df$group = (1:nrow(df) - 1) %/% 200` and create the vector of values to divide by `div` for each corresponding group then do `df$conc / div[df$group]`. – Gregor Thomas Dec 01 '22 at 15:20
  • 2
    Your question here seems to be about how to process a frame by groups of rows. Please remove the [tag:shiny] tag, all shiny-related code, and reduce this to the minimum code required to reproduce the issue. On that note, making the question _reproducible_ would greatly help: this includes sample *unambiguous* data (e.g., `data.frame(x=...,y=...)` or the output from `dput(head(x))`) and intended output given that input. Refs: https://stackoverflow.com/q/5963269, [mcve], and https://stackoverflow.com/tags/r/info. – r2evans Dec 01 '22 at 15:22

0 Answers0