1

我正在寻找一种优雅的方式来创建这些数据的表:

我有一个我感兴趣的日期向量

> date
[1] "2008-01-01" "2008-01-02" "2008-01-03" "2008-01-04" "2008-01-05"

以及来自维基百科的数据表(每天的浏览量)

> changes
2007-08-14 2007-08-16 2007-08-17 2007-12-29 2008-01-01 2008-01-03 2008-01-05 
         4          1          4          1          1          1          2 

我想要的是一张包含我感兴趣的日期数据的表格

> mytable
2008-01-01 2008-01-02 2008-01-03 2008-01-04 2008-01-05
         1          0          1          0          2

谁能给我一个关于如何优雅地做到这一点的提示?


这是dput的输出:

> dput(date)
structure(c(13879, 13880, 13881, 13882, 13883), class = "Date")

> dput(changes)
structure(c(15L, 2L, 9L, 1L, 1L, 1L, 3L), .Dim = 262L, .Dimnames = structure(list(
c("2007-08-14", "2007-08-16", 
"2007-08-17", "2007-12-29", "2008-01-01", "2008-01-03", "2008-01-05")), .Names = ""), class = "table")
4

1 回答 1

1

我想使用match将是最简单的方法。您需要使用as.character才能将日期与更改的名称相匹配table...

#  Match dates in the names of 'changes' vector. No match gives NA
#  Using setNames we can return the object and set the names in one command
mytable <- setNames( changes[ match(as.character(date) , names(changes)) ] , date )

#  Change NA values to 0 (is this sensible? Does no data mean 0 views or was the data not available?)
mytable[ is.na(mytable) ] <- 0

mytable
#2008-01-01 2008-01-02 2008-01-03 2008-01-04 2008-01-05 
#         1          0          1          0          3 
于 2013-09-17T08:27:24.827 回答