如何转换为时间序列并绘制每天作为变量或列的数据框? [英] How to convert to a time series and plot a dataframe with each day as a variable or column?

查看:48
本文介绍了如何转换为时间序列并绘制每天作为变量或列的数据框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试绘制意大利 Cov-19 数量随时间变化的图,并发现了这个

<小时>

某些值为 0,因此将它们转换为 NA,因为当 log2 转换完成时,它会导致 Inf

库(dplyr)plot(xts(log(na_if(unlist(Italy), 0), 2), order.by = as.Date(sub("X", "", names(Italy)),"%m.%d.%y")), main = 'xts log2 plot')

I am trying to get a plot of the number of Cov-19 in Italy over time, and came across this repository in GitHub, and tried to subset the data for Italy as such:

require(RCurl)
require(foreign)
x = getURL("https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_19-covid-Confirmed.csv")
corona = read.csv(text = x, sep =",",header = T)
str(corona)
Italy <- corona[,corona$Country.Region=='Italy']
Italy <- corona[corona$Country.Region=='Italy',][1,5:ncol(corona)]
head(Italy)[,45:52]

which outputs:

> head(Italy)[,45:52]
   X3.6.20 X3.7.20 X3.8.20 X3.9.20 X3.10.20 X3.11.20 X3.12.20
17    4636    5883    7375    9172    10149    12462    12462
   X3.13.20
17    17660

Converting this to a time series with xts led me to several posts asking how to convert a database to a time series, where every day is a row in the variable Date, but in this dataframe it seems as though the each date is a variable.

I don't necessarily need to get this formatted as a time series, but I would like to plot over time the number of cases.


Here is a way to bypass timeseries:

require(RCurl)
require(foreign)
x = getURL("https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_19-covid-Confirmed.csv")
corona = read.csv(text = x, sep =",",header = T)
str(corona)
Italy <- corona[,corona$Country.Region=='Italy']
Italy <- corona[corona$Country.Region=='Italy',][1,5:ncol(corona)]
Italy <- as.matrix(sapply(Italy, as.numeric))
plot(Italy[,1],typ='l',xlab='', ylab='', col='red', lwd=3,
     main="Italy Cov-19 cum cases")

解决方案

We can convert to xts and plot

library(xts)
plot(xts(unlist(Italy), order.by = as.Date(sub("X", "", names(Italy)),
        "%m.%d.%y")), , main = "xts plot")


Some values are 0, so converting those to NA as it can lead to Inf values when the log2 conversion is done

library(dplyr)
plot(xts(log(na_if(unlist(Italy), 0), 2), order.by = as.Date(sub("X", "", names(Italy)),
     "%m.%d.%y")), main = 'xts log2 plot')

这篇关于如何转换为时间序列并绘制每天作为变量或列的数据框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆