我正在寻找一种优雅的方法来创建这个数据的表格:
我有一个我感兴趣的日期矢量
> 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")
答案 0 :(得分: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