Fill down over existing values

Hello,
I know how to use fill down with tidyr.
But I now need to perfomr a task a bit tricky for me.

I need to fill down one variable using the first value of a vector as mark sign.


df<-data.frame(

A=c(1,2,2,3,3,3,4,4,4,4)
B=c(100,200,220,300,330,333,400,440,444,444.4)
)



desired<-data.frame(D=c(100,200,200,300,300,300,400,400,400,400)

As you can see, It's kind of fill down but using as reference the vector named A for changing the values, for erasing the row value and using the first appearance in the group (vector A).
I have no idea how to do it. For example, if the vector B were:

B=c(100,200,NA,300,NA,NA,400,NA,NA,NA)

That task would be simpler. But I'm using A and erasing B.
Thanks for your time and interest.
Have a nice weekend.

Hi,

Could you say more? It's not quite clear why you need a fill()-like process since you have the reference vector A in your table. For example, why wouldn't you use mutate(df, B = 100 * A)?

Just group your data and combine it with your desired tidyverse function. Use first(), last(), nth() to get the respective value - group first to get the respective value of each group. The same logic applies to fill().

library(tidyverse)

df <-data.frame(
  A = c(1,2,2,3,3,3,4,4,4,4),
  B = c(100,200,220,300,330,333,400,440,444,444.4),
  B2 = c(100,200,NA,300,NA,NA,400,NA,NA,NA)
)

df %>% group_by(A) %>% mutate(desired = first(B))
df %>% group_by(A) %>% fill(B2, .direction = "down")