consolidating code questions

hi I have the following code chunk. is there any way to make the mutate and different fills in fewer lines of code? basically I copy a given column and then I select the fill's direction based on the new suffix of the column.

data %>%
mutate(copy_down = copy,
copy_up = copy,
copy_updown = copy,
copy_downup = copy) %>% 

group_by(ID, period) %>% 

fill(copy_down, .direction = "down") %>% 
fill(copy_up, .direction = "up") %>% 
fill(copy_updown, .direction = "updown") %>% 
fill(copy_downup, .direction = "downup") 

thank u <3

if anyone can help id love it!!! <3 thanku!!

Hi @help ,

I'm not sure we have enough information about what it is you are trying to do based on your example. Will you explain in more detail what your goal is, and maybe an example of what the data looks like, and what you want it to look like at the end of your transformation?

1 Like

library(tidyverse)
mydata <- data.frame(
  copy = c(1:4, NA, 5:7, NA, NA, 99)
)
p <- c("down", "up", "updown", "downup")

fs <- map(
  p,
  ~ {
    function(data) {
      nm <- paste0("copy_", .x)
      fill(transmute(data, !!nm := copy), nm, .direction = .x)
    }
  }
) %>% set_names(paste0("fill_", p))


bind_cols(mydata,map_dfc(fs,~
      .x(mydata)))
1 Like

This topic was automatically closed 42 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.