r - Divide case by population -


in table2 dataset tidyr package, have:

  country  year       type      count          <chr> <int>      <chr>      <int>  1 afghanistan  1999      cases        745  2 afghanistan  1999 population   19987071  3 afghanistan  2000      cases       2666  4 afghanistan  2000 population   20595360  5      brazil  1999      cases      37737  6      brazil  1999 population  172006362  7      brazil  2000      cases      80488  8      brazil  2000 population  174504898  9       china  1999      cases     212258 10       china  1999 population 1272915272 11       china  2000      cases     213766 12       china  2000 population 1280428583 

how code can divide type cases type population , multiply 10000. (yes, question r data science hadley wickham.)

i've thought of:

sum_1 <- vector() (i,j in 1:nrow(table2)) {   if (i %% 2 != 0) {     sum_1 <- (table2[i] / table2[j]) * 10000 

assuming there 2 values 'type' each 'country', 'year', after grouping 'country', 'year', arrange 'type' (in case order different) , divide first value of 'count' last value of 'count' create 'newcol'

library(dplyr) table2 %>%     group_by(country, year) %>%     arrange(country, year, type) %>%      mutate(newcol = 10000*first(count)/last(count)) 

if need summarised output, replace mutate summarise


if there other values in type in addition 'cases' , 'population', subset 'count' based on logical index

table2 %>%     group_by(country, year) %>%     mutate(newcol = 10000*count[type=="cases"]/count[type=="population"]) 

here, assumption there single 'cases' , 'population' per each 'country', 'year'


Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -