change the value of a variable depending on other variables

Hi!
In this dataframe, which I have data for US's states population for different time periods, I want to set the population of every state to its first available period's population:

This is my dataset:

state <- c(Alabama, Alabama, Alabama, Arkansas, Arkansas, Arkansas, Arkansas)
year<- c(1990, 1991, 1992, 2002, 2003, 2005, 2011)
population <- c(10000, 11000, 12000, 23000, 24000, 25000, 30000)
df <- data.frame( state, year, population)

I want to obtain this:

state <- c(Alabama, Alabama, Alabama, Arkansas, Arkansas, Arkansas, Arkansas)
year<- c(1990, 1991, 1992, 2002, 2003, 2005, 2011)
population <- c(10000, 10000, 10000, 23000, 23000, 23000, 23000)
df <- data.frame( state, year, population)

This is just a small fraction of my full dataset, so I need a code to not change constantly the state's name.

Thanks!

It doesn't seem to have anything different with the code block beyond, missed something?

But I read this

you can try:

library(dplyr)

df |> group_by(state) |> filter(year == min(year))
# A tibble: 2 x 3
# Groups:   state [2]
  state     year population
  <chr>    <dbl>      <dbl>
1 Alabama   1990      10000
2 Arkansas  2002      23000

With this code I loose the other observations, i still need the 7 observations with the population of the first year per every state.

Thanks

sorry I missed that, try this

df %>% group_by(state) %>% mutate(
  detect_1st_y = year == min(year),
  population = (population * detect_1st_y) %>% na_if(0)
) %>% fill(population) %>% select(-detect_1st_y)

# A tibble: 7 x 3
# Groups:   state [2]
  state     year population
  <chr>    <dbl>      <dbl>
1 Alabama   1990      10000
2 Alabama   1991      10000
3 Alabama   1992      10000
4 Arkansas  2002      23000
5 Arkansas  2003      23000
6 Arkansas  2005      23000
7 Arkansas  2011      23000

This topic was automatically closed 21 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.