Using approx() with groups in dplyr

后端 未结 1 1522
面向向阳花
面向向阳花 2021-01-28 10:07

I am trying to use approx() and dplyr to interpolate values in an existing array. My initial code looks like this ...

p = c(1,1,1,2,2,         


        
相关标签:
1条回答
  • 2021-01-28 10:55

    You can get the values you expect using dplyr.

    library(dplyr)
    Inputs %>%
      group_by(p) %>%
      arrange(p, q, .by_group = TRUE) %>%
      summarise(new.outputs = approx(x = q, y = r, xout = new.inputs)$y)
    
    #     p  new.outputs
    #  <dbl>       <dbl>
    #     1         1.5
    #     1         2.5
    #     2         4.5
    #     2         5.5
    

    You can also get the values you expect using the ddply function from plyr.

    library(plyr)
    
    # Output as coordinates
    ddply(Inputs, .(p), summarise, new.output = paste(approx(
      x = q, y = r, xout = new.inputs
    )$y, collapse = ","))
    
    # p new.output
    # 1    1.5,2.5
    # 2    4.5,5.5
    
    #######################################
    
    # Output as flattened per group p
    ddply(Inputs,
          .(p),
          summarise,
          new.output = approx(x = q, y = r, xout = new.inputs)$y)
    
    # p new.output
    # 1        1.5
    # 1        2.5
    # 2        4.5
    # 2        5.5
    
    
    0 讨论(0)
提交回复
热议问题