commfish / coho_known_age_study

1 stars 1 forks source link

multiple sums #7

Open ben-williams opened 5 years ago

ben-williams commented 5 years ago

https://github.com/commfish/coho_known_age_study/blob/cd4195797bcd2ec24ba3940d889a8d5be0eaa528/code/LDA_JTP_DataImport.R#L160

  1. I strongly encourage not naming something j or A etc. as they are not terribly informative

Instead of using massively long sums possibly use something such as:

library(tidyverse)
f_sum <- function(data, col1, col2, div){
  col1 = enquo(col1)
  col2 = enquo(col2)
  div = enquo(div)

  data %>% 
    dplyr::select(!!col1:!!col2) %>% 
    apply(1, sum, na.rm=T) %>% 
    as.data.frame %>% 
    bind_cols(data) %>% 
    transmute(temp = . / !!div) %>% 
    .$temp
}  

data.frame(a = 1:10,
           b = abs(rnorm(10)),
           c=abs(rnorm(10)),
           d=abs(rnorm(10)),
           e=abs(rnorm(10)),
           f=abs(rnorm(10)),
           g=abs(rnorm(10)),
           h=abs(rnorm(10))) %>% 
  mutate(q5 = f_sum(., c, d, b),
         q6 = f_sum(., c, e, b),
         q7 = f_sum(., c, f, b),
         q8 = f_sum(., c, g, b))

Or some variant thereof?

justinpriest commented 5 years ago

Thanks @ben-williams. I'm still in the process of making the dataset completely tidyverse dependent and equivalent to what it was before. I haven't gotten to the lines yet that you reference. The variable names are not yet finalized and that will only be done once I've completed updating the script. The names are what they are (e.g., "j_JTP) so that I can compare similarly name variables in the SEM code (e.g., "j"). Thanks for the function to sum. I was just playing with something similar yesterday and automatically pasting column names; unfortunately using paste0() in mutate causes an error because of a special character issue. So I'll use your function or something similar.