DF <- data.frame(
Northwest = as.factor(c("Increased region", "2006", "2007", NA)),
Northwest.1 = as.factor(c("Remained region", "2011", "2012", "2013")),
Northeast = as.factor(c("Increased region", "2006", "2007", NA)),
Red.River.Delta = as.factor(c("Increased region", "2011", "2012", "2013"))
)
library(tidyr)
library(dplyr)
library(stringr)
DFnew <- gather(DF, key = "Region", value = "Val") %>%
filter(!is.na(Val)) %>%
mutate(Label = ifelse(str_detect(Val, "^\\d+$"), NA, Val)) %>% #keep non-numeric text
fill(Label) %>% #replace NA with previous text
filter(str_detect(Val, "^\\d+$")) %>% #keep only numeric text
mutate(Region = str_replace_all(Region, "\\.|\\d", " ")) %>%
mutate(Region = str_trim(Region))
#> Warning: attributes are not identical across measure variables;
#> they will be dropped
DFnew
#> Region Val Label
#> 1 Northwest 2006 Increased region
#> 2 Northwest 2007 Increased region
#> 3 Northwest 2011 Remained region
#> 4 Northwest 2012 Remained region
#> 5 Northwest 2013 Remained region
#> 6 Northeast 2006 Increased region
#> 7 Northeast 2007 Increased region
#> 8 Red River Delta 2011 Increased region
#> 9 Red River Delta 2012 Increased region
#> 10 Red River Delta 2013 Increased region