如何最好地拆开它并制作一个长数据字符串
How best to unstack this and make for one long data string
下面是样本数据和期望的结果。是的,我知道有四列没有列在所需的列中。这只是为了保持简单。想一想如果我能创建前四个,那么接下来的四个还不错。关于如何实现这一目标的任何想法?我的第一次尝试是使用 pivot_wider,但努力获取要创建的年份和月份的列名。
state <- c(32,32,32,32,32,32,32,32)
indcode <-c(44,44,44,44,45,45,45,45)
area <-c("000000","000000","000000","000000","000000","000000","000000","000000")
areatype <-c("01","01","01","01","01","01","01","01")
ownership <-c("00","00","00","00","00","00","00","00")
periodyear <-c(2018,2019,2020,2021,2018,2019,2020,2021)
January <- c(44,90,45,91,46,92,48,96)
February <- c(44,91,46,91,48,92,49,99)
example <- data.frame(state,indcode,area,areatype,ownership,periodyear,January,February)
state indcode area areatype ownership 2018m1 2018m2 2019m1 2019 m2
32 44 000000 01 00 44 44 90 91
32 45 000000 01 00 46 48 92 92
library(tidyverse)
example %>%
pivot_longer(January:February, names_to = "month") %>%
mutate(mo_num = match(month, month.name)) %>%
mutate(col_name = paste(periodyear, mo_num, sep = "m")) %>%
select(-periodyear, -month, -mo_num) %>%
pivot_wider(names_from = col_name, values_from = value)
结果
# A tibble: 2 x 13
state indcode area areatype ownership `2018m1` `2018m2` `2019m1` `2019m2` `2020m1` `2020m2` `2021m1` `2021m2`
<dbl> <dbl> <chr> <chr> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 32 44 000000 01 00 44 44 90 91 45 46 91 91
2 32 45 000000 01 00 46 48 92 92 48 49 96 99
下面是样本数据和期望的结果。是的,我知道有四列没有列在所需的列中。这只是为了保持简单。想一想如果我能创建前四个,那么接下来的四个还不错。关于如何实现这一目标的任何想法?我的第一次尝试是使用 pivot_wider,但努力获取要创建的年份和月份的列名。
state <- c(32,32,32,32,32,32,32,32)
indcode <-c(44,44,44,44,45,45,45,45)
area <-c("000000","000000","000000","000000","000000","000000","000000","000000")
areatype <-c("01","01","01","01","01","01","01","01")
ownership <-c("00","00","00","00","00","00","00","00")
periodyear <-c(2018,2019,2020,2021,2018,2019,2020,2021)
January <- c(44,90,45,91,46,92,48,96)
February <- c(44,91,46,91,48,92,49,99)
example <- data.frame(state,indcode,area,areatype,ownership,periodyear,January,February)
state indcode area areatype ownership 2018m1 2018m2 2019m1 2019 m2
32 44 000000 01 00 44 44 90 91
32 45 000000 01 00 46 48 92 92
library(tidyverse)
example %>%
pivot_longer(January:February, names_to = "month") %>%
mutate(mo_num = match(month, month.name)) %>%
mutate(col_name = paste(periodyear, mo_num, sep = "m")) %>%
select(-periodyear, -month, -mo_num) %>%
pivot_wider(names_from = col_name, values_from = value)
结果
# A tibble: 2 x 13
state indcode area areatype ownership `2018m1` `2018m2` `2019m1` `2019m2` `2020m1` `2020m2` `2021m1` `2021m2`
<dbl> <dbl> <chr> <chr> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 32 44 000000 01 00 44 44 90 91 45 46 91 91
2 32 45 000000 01 00 46 48 92 92 48 49 96 99