You can achieve this also with gather
/spread
approach:
library(dplyr)
df <- structure(list(`1997` = c(0, 0, 1, 0, 0, 0, 0, 0, 0, 0),
`1998` = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
`1999` = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
`2000` = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
allyrs = c(FALSE, FALSE, TRUE, FALSE,
FALSE, TRUE, FALSE, TRUE, TRUE, FALSE)),
class = c("tbl_df", "tbl", "data.frame"),
row.names = c(NA, -10L))
df %>%
tidyr::gather(key = "year", value = "value", -allyrs) %>%
dplyr::group_by(year) %>%
dplyr::mutate(row = dplyr::row_number()) %>%
dplyr::mutate(value = ifelse(allyrs == TRUE, 1, 0)) %>%
tidyr::spread(key = year, value = value) %>%
dplyr::select(-row)
#> # A tibble: 10 x 5
#> allyrs `1997` `1998` `1999` `2000`
#> <lgl> <dbl> <dbl> <dbl> <dbl>
#> 1 FALSE 0 0 0 0
#> 2 FALSE 0 0 0 0
#> 3 FALSE 0 0 0 0
#> 4 FALSE 0 0 0 0
#> 5 FALSE 0 0 0 0
#> 6 FALSE 0 0 0 0
#> 7 TRUE 1 1 1 1
#> 8 TRUE 1 1 1 1
#> 9 TRUE 1 1 1 1
#> 10 TRUE 1 1 1 1
Created on 2018-11-02 by the reprex package (v0.2.1)