Search code examples
rdataframeinner-joindata-cleaning

Writing a cleaner version of code to improve readability


I am fairly new to R and I am hoping to know if there is a cleaner way of writing the code below. Basically, I am dropping a few duplicates from df1 and appending them to df2. I am then joining the values from count_df to df2 and renaming certain columns in df2.

I would really like to do all of this under a single code block as opposed to the way I have done it below. However, I keep running very different errors every time I try to put this all under a single code block. This is just a single instance, but I have had to do this multiple times already in my code. I would greatly appreciate any input on how to improve the code below. Thank you!

df2 <- df1 %>%
  distinct(ID, Temp, .keep_all = TRUE) %>%
  summarise(n())

df2 <- df2 %>%
  inner_join(count_df, by = c("ID" = "ID"))

df2 <- df2 %>%
  rename(unique_dps = `n()`,inital_dps = n)

Solution

  • We can have this in the same %>%

    library(dplyr)
    count_df %>%
            add_count(ID, Temp) %>% 
            rename(unique_dps = n)