我使用以下方法从 R 中的 SQL 数据框中检索数据:
query <- "SELECT date, identifier, somevalue FROM mytable"
data <- sqlQuery(conn, query)
这给了我:
> data
date identifier somevalue
1 2011-01-01 1 0.50
2 2011-01-02 1 0.40
3 2011-01-01 2 0.70
4 2011-01-02 2 0.10
5 2011-01-03 2 0.25
data <- data.frame(date=c("2011-01-01","2011-01-02","2011-01-01","2011-01-02","2011-01-03"), identifier=c(1,1,2,2,2), somevalue=c(0.5,0.4,0.7,0.1,0.25))
我想将其转换为使用日期作为行名和标识符作为列名的数字矩阵:
> output
1 2
2011-01-01 0.5 0.70
2011-01-02 0.4 0.10
2011-01-03 NA 0.25
output <- matrix(c(0.5,0.4,NA,0.7,0.1,0.25),3)
rownames(output) <- c("2011-01-01","2011-01-02","2011-01-03")
colnames(output) <- c(1,2)
我不知道该怎么做。我已经调查过reshape
并且也调查过,match
但由于有重复的行名或标识符,我总是失败。