将开始和年末的数据R转换为时间序列数据

yfwxisqw  于 2023-02-20  发布在  其他
关注(0)|答案(1)|浏览(139)

我有一个与此非常相似的问题:
R transform data frame with start and end year into time series然而,没有一种解决方案对我有效。
这是原始df:

df <- data.frame(country = c("Albania", "Albania", "Albania"), leader = c("Sali Berisha", "Sali Berisha", "Sali Berisha"), term = c(2, 2, 2), yearbegin = c(2009,2009, 2009), yearend = c(2013, 2013, 2013))

它现在看起来像这样:

#>    country    leader         term  yearbegin  yearend
#> 1   Albania    Sali Berisha    2    2009       2013
#> 2   Albania    Sali Berisha    2    2009       2013
#> 3   Albania    Sali Berisha    2    2009       2013

我试着把它做成这样:

#> 1    Albania  Sali Berisha   2      2009
#> 2    Albania  Sali Berisha   2      2010
#> 3    Albania  Sali Berisha   2      2011
#> 4    Albania  Sali Berisha   2      2012
#> 5    Albania  Sali Berisha   2      2013

使用此代码时:

library(tidyverse)
 gpd_df<- gpd_df %>% 
  mutate(year = map2(yearbegin, yearend, `:`)) %>% 
  select(-yearbegin, -yearend) %>% 
  unnest```

I get a column that looks like this:

```year
2009:2013
2009:2013
2009:2013

提前感谢您的帮助!!
正在尝试将日期转换为时间序列形式的年开始/年结束。刚刚发现错误:“)

bkhjykvo

bkhjykvo1#

首先使用distinct

library(dplyr)
library(tidyr)
gpd_df %>% 
  distinct() %>% 
  mutate(year = map2(yearbegin, yearend, `:`), .keep = "unused") %>% 
  unnest_longer(year)

  country leader        term  year
1 Albania Sali Berisha     2  2009
2 Albania Sali Berisha     2  2010
3 Albania Sali Berisha     2  2011
4 Albania Sali Berisha     2  2012
5 Albania Sali Berisha     2  2013

相关问题