R:创造这张桌子的优雅方式

时间:2022-12-22 19:32:42

I'm looking for an elegant way to create a table of this data:

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

I have a vector of dates I am interested in

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

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

and a table of data from wikipedia (views per day)

和来自*的数据表(每日观看次数)

> 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 

What I want is a table with the data for the dates I am interested in

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

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

Can anyone give me a hint on how to do this elegantly?

任何人都可以给我一个如何优雅地做这件事的提示吗?


Here is the output of dput:

这是dput的输出:

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

and

> 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")

1 个解决方案

#1


1  

I guess using match would be the easiest way. You need to use as.character to be able to match dates to the names of your changes table...

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

#  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 

#1


1  

I guess using match would be the easiest way. You need to use as.character to be able to match dates to the names of your changes table...

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

#  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