-4

I have a dataframe with three columns - state names, dates, and a numerical values.

The matrix I am trying to create needs to have the state names as row names, and the dates as the column names, with the numerical values within the matrix. Obviously, there will be many NA values within the matrix. (there are 51 'states' and 84 dates). I've been working on this all day and the closest I've gotten is creating a dataframe with the correct number of dates and state names corresponding to each other, but the numerical values don't match up.

there are 84 dates, but not every state has 84 corresponding dates.

Goal = all states only are listed once alphabetical order... all dates only listed once... fill in empty spaces w/ NA

enter image description here Thanks

Cedric
  • 2,412
  • 17
  • 31

1 Answers1

1

Welcome to stackoverflow. When you post a question on stackoverflow it's better if you include an example of the data that you are trying to produce, look there : reproducible example. You'll get much faster responses even if your questions are trivial. Below, most of the lines of code do reproduce your example :

# create vector of random dates
dates <- as.Date(sample( as.numeric(as.Date('2015-01-01')): as.numeric(as.Date('2018-01-01')), 200, 
        replace = T), 
    origin = '1970-01-01')
# create vector of states
library(datasets)
data(state)
name<-state.name 
# create random number
values <- rnorm(50)

This is one of the ways to produce what you want

require(tidyverse)
df <- data.frame(dates, name, values)
df%>%spread(key=dates,value=values)%>%head(20)
Cedric
  • 2,412
  • 17
  • 31