-4
rookie_1_team$year[1:5] <- "2018"
rookie_1_team$year[6:10] <- "2017"
rookie_1_team$year[11:15] <- "2016"
rookie_1_team$year[16:20] <- "2015"
rookie_1_team$year[21:25] <- "2014"

Is there a way to write this in a for loop or a function instead of just manually putting it in all the way to 2000. Or maybe an apply?

So it would be a sequence of 5 before going down a year to then go to the next year like 2017. Then go through 5 again filling out 2017 then go down one again to 2016.

Any hints or help would be great. Still very new to R.

Thanks in advance.

enter image description here

黄日华
  • 1
  • 1
  • 1
    Hi there, it's better(best) to add data to your question using `dput(head(mydata,20))`. – NelsonGon Dec 23 '18 at 11:54
  • 1
    `rookie_1_team$year[1:5]` is a vector, i.e. has no dimensions. Read `help("rownames<-")` – markus Dec 23 '18 at 11:56
  • 2
    if the *missing* entries are `NA` you can use `zoo::na.locf` , see https://stackoverflow.com/questions/7735647/replacing-nas-with-latest-non-na-value , but we can't tell if this is the case from a screenshot – user20650 Dec 23 '18 at 12:00

1 Answers1

2

Try this one:

 df <- data.frame(
   year=c("2018","","","","2017","",""),
   x=c(1:7))
 library(tidyverse)
 df %>% 
   mutate(year=as.numeric(as.character(year))) %>% 
   fill(year)
  year x
1 2018 1
2 2018 2
3 2018 3
4 2018 4
5 2017 5
6 2017 6
7 2017 7
jyjek
  • 2,627
  • 11
  • 23