2

I'm trying to make some barplots with data from the IMF. I tried to read the xls file with read.table():

base <- read.table("http://www.imf.org/external/pubs/ft/weo/2017/02/weodata/WEOOct2017all.xls", header=TRUE, sep="\t", fill=TRUE)

However, the data is saved as a list:

typeof(base)
[1] "list"

And I don't know how to extract the data to make a barplot. For example, I want to graph the variable "NGDP_RPCH", for the country "ARG" and the years 2010-2019 (columns 40-49 in the excel).

I tried this, but it didn't work:

graph <- base[which((base[2]=="ARG")&(base[3]=='NGDP_RPCH')),40:49]
graph
[1] X2010 X2011 X2012 X2013 X2014 X2015 X2016 X2017 X2018 X2019
<0 rows> (or 0-length row.names)

I would like to know how to save the data as a data frame, or how to extract a vector of data from the list, so I could run:

barplot(graph).
amonk
  • 1,769
  • 2
  • 18
  • 27
esterodr
  • 117
  • 1
  • 7
  • 1
    The title of the duplicate references .xlsx files, but the solutions presented there generally work for both those and older .xls files as well. – joran Oct 11 '17 at 19:45
  • For any data.frame, it's true `typeof(base)=="list"`. Use `class()`, not `typeof()` to see how an object behaves, not how it's stored. I would guess `class(base)` is "data.frame" – MrFlick Oct 11 '17 at 19:51
  • For your second question, there is no "NGDP_RPCH" for "ARG" as the country. Are you sure "NGDP_RPCH" is the correct variable? – Ran Tao Oct 11 '17 at 19:58
  • File 228 of the excel: 213 ARG NGDP_RPCH Argentina – esterodr Oct 11 '17 at 20:04

1 Answers1

7

First, use an appropriate tool to import Excel files. This may include the packages readxl, openxlsx, XLConnect, xlsx, etc.

library(readxl)
base <- read_excel("~/Desktop/WEOOct2017all.xls")

Then use [[ to select a single column, not [.

graph <- base[which((base[[2]]=="ARG")&(base[[3]]=='NGDP_RPCH')),40:49]

And convert to a matrix to use barplot.

barplot(as.matrix(graph))
joran
  • 169,992
  • 32
  • 429
  • 468