0

My goal is to have a list of how much FDI China sent to each country per year. At the moment I have a list of individual projects that looks like this

Year Country Amount
2001 Angola 6000000
2001 Angola 8000000
2001 Angola 5.0E7

I want to sum it so it looks like this.

Year Country Amount
2001 Angola 6.4E7

How do I merge the rows and add the totals to get nice country-year data? I can't find an R command that does this precise thing.

some dude
  • 3
  • 1

1 Answers1

1
library(tidyverse)

I copied the data table and read your dataframe into R using:

df <- clipr::read_clip_tbl(clipr::read_clip())

I like using dplyr to solve this question:

df2 <- as.data.frame(df %>% group_by(Country,Year) %>% summarize(Amount=sum(Amount)))

# A tibble: 1 x 3
# Groups:   Country [1]
  Country  Year   Amount
  <chr>   <int>    <dbl>
1 Angola   2001 64000000
ecology
  • 606
  • 3
  • 9
  • 29
  • I got an error message Error in data3 %>% group_by(recipient_cow_code, Year) %>% summarize(usd_current = sum(usd_current)) : could not find function "%>%" – some dude Apr 30 '21 at 20:26
  • 1
    i think the dplyr package is masked by another pakcage. please run rm(list=ls()) at the beginning of the script and load only tidyverse and not purr and tell us what you see – LDT Apr 30 '21 at 20:56
  • Perhaps plyr is the issue? – ecology Apr 30 '21 at 21:03
  • make sure dplyr is installed and loaded before running the script, @somedude – GuedesBF Apr 30 '21 at 21:15
  • I installed dplyr, still the same error message. No result from rm(list=ls()) – some dude Apr 30 '21 at 21:37
  • Do you see dplyr and/or plyr loaded in the packages tab? @somedude – ecology Apr 30 '21 at 22:00
  • I turned on dplyr and it outputted a bunch of (what I think is) merged data in the console. If I can turn that into a dataframe I'm done. – some dude May 01 '21 at 00:03
  • @somedude See my edit :) you just have to assign it to a dataframe structure. The output was a tibble but I prefer to have everything in a dataframe – ecology May 01 '21 at 00:22