S31
S31

Reputation: 934

Returning empty data table when subsetted

I'm working with someone else's code and re-running it to piece together what they did. It seems like this portion of code I'm running is returning an empty data.table, which is not ideal. The code below can be ran.

url = "http://www.cpc.ncep.noaa.gov/products/analysis_monitoring/ensostuff/ensoyears.shtml" 
page <- readLines(url)
ONI_data_raw <- data.table (readHTMLTable(page, which=8))
headers <- c ("Year", 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)
setnames(ONI_data_raw, headers)
ONI_data_raw = melt(ONI_data_raw, id.vars = "Year")
names(ONI_data_raw)[2] = "Month"
names(ONI_data_raw)[3] = "ONI_Value"
ONI_data_raw$Month = as.numeric(ONI_data_raw$Month)
ONI_data_raw$ONI_Value= as.numeric(ONI_data_raw$ONI_Value)
ONI_data_raw = subset(ONI_data_raw, ONI_data_raw$Year %in% time )
head(ONI_data_raw)

The result I get is:

Empty data.table (0 rows) of 3 cols: Year,Month,ONI_Value

Ideally what I would like to see is something like this:

Year          Jan           Feb          March    etc. 
1950         -1.4          -1.2          -1.1
1951         -0.8          -0.6          -0.2

I assume this was the goal of the code, but if you run the third to last line (before it was subset), the output is kind of funky

    Year Month ONI_Value
 1: 1950     1      -1.4
 2: 1951     1      -0.8
 3: 1952     1       0.5
 4: 1953     1       0.5
 5: 1954     1       0.7
 6: 1955     1      -0.6
 7: 1956     1      -0.9
 8: 1957     1      -0.3
 9: 1958     1       1.7
10: 1959     1       0.6
11: Year     1        NA
12: 1960     1      -0.1

Where row 11 is the odd one. A couple more rows do that as well. Not sure if that's causing the problem, but once the second to last line is ran - the data table comes up empty.

Any insight would be helpful!

Upvotes: 0

Views: 81

Answers (1)

Geovani Ferreira
Geovani Ferreira

Reputation: 86

what is "time" in this line?

ONI_data_raw = subset(ONI_data_raw, ONI_data_raw$Year %in% time )

if I assume time = c(1950,1951), you need use a spread function from tydir package

spread(ONI_data_raw, Month, ONI_Value)

the problem you say Is probably caused by this subset line.

Upvotes: 1

Related Questions