How can I make a counter for every country using a loop? R

守給你的承諾、 提交于 2021-02-11 04:31:48

问题


I think this is very easy but I have no idea how to do it (or how to search it).

Okay so I got 378 observations for a lot of countries.

It goes like this

ISO3C       Date     Country    Vaccines Tests Confirmed Recovered Death Hospitalized Ventilation ICU
1   AFG 2020-01-01 Afghanistan        0     0         0         0     0            0           0   0
2   AFG 2020-01-02 Afghanistan        0     0         0         0     0            0           0   0
3   AFG 2020-01-03 Afghanistan        0     0         0         0     0            0           0   0
4   AFG 2020-01-04 Afghanistan        0     0         0         0     0            0           0   0
5   AFG 2020-01-05 Afghanistan        0     0         0         0     0            0           0   0

So How do I set a counter that jan 1st 2020 is 1 till today (2021-01-12) that is day no. 378, and then start over if Country changes

and what if the first day isn't jan 1st, 2020, but each country has it own start date?


回答1:


You can subtract the first(Date) from each country.

library(dplyr)

df %>% 
  arrange(ISO3C, Date) %>%
  group_by(ISO3C) %>% 
  mutate(counter = Date - first(Date) + 1) -> result

result



回答2:


Actually grouping won't change anything but since you want it

df %>% group_by(ISO3C) %>% mutate(counter= Date - as.Date("01-01-2020"))

this will work

df %>% mutate(counter= Date - as.Date("01-01-2020"))

EDIT

df %>% inner_join(df_origins) %>% mutate(counter= Date - Origin) %>% select(!Origin)

where df_origins has columns Country and Origin



来源:https://stackoverflow.com/questions/65694056/how-can-i-make-a-counter-for-every-country-using-a-loop-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!