1

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(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
  • Add the output of dput(changes) and dput(date). It'll take all the guess work out of what exactly your data looks like. I'm guessing a vector and a named vector. Sep 17, 2013 at 8:20

1 Answer 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...

#  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 
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.