我有一个数据框(df),其中包含一列日期和一列数字(1,2或3),如下所示:
Date Number
01/01/2014 1
01/01/2014 1
01/01/2014 2
01/01/2014 3
02/01/2014 3
02/01/2014 2
02/01/2014 2
02/01/2014 2
03/01/2014 1
03/01/2014 3
我使用split:
按日期拆分此数据框 days <- split(df, df$Date)
然后我想在分割数据框中的每一天应用一个函数来计算每天发生“1”,“2”或“3”的次数。这就是我所拥有的:
myfunction <- function(df){
One <- length(which(df$Number==1))
Two <- length(which(df$Number==2))
Three <- length(which(df$Number=="NA"))
}
lapply(days, myfunction)
如果我使用例如打印(一)在此功能结束时,它将打印每天出现1次的次数。但是,我想创建一个新的数据框,其中包含日期和每个数字出现的次数,如下所示:
Date 1 2 3
01/01/2014 2 1 1
02/01/2014 0 3 1
03/01/2014 1 0 1
当我尝试将其写入我的函数时,我只得到一行数据帧。这是我的代码:
myfunction <- function(df){
One <- length(which(df$Number==1))
Two <- length(which(df$Number==2))
Three <- length(which(df$Number=="NA"))
newdataframe<- data.frame(One=One, Two=Two, Three=Three)
write.csv(newdataframe, file="12345.csv")
}
lapply(days, myfunction)
以下是我收到的错误:
Error in file(file, ifelse(append, "a", "w")) :
cannot open the connection
In addition: Warning message:
In file(file, ifelse(append, "a", "w")) :
cannot open file '12345.csv': Permission denied
我也尝试过append = TRUE。
注意 - 我还没有把日期添加到我的新数据框中。
答案 0 :(得分:1)
使用xtabs
(或table
)会让您的生活更轻松。
(mat <- xtabs( ~ Date + Number, data = df))
## Number
## Date 1 2 3
## 01/01/2014 2 1 1
## 02/01/2014 0 3 1
## 03/01/2014 1 0 1
colnames(mat) <- c("one", "two", "three")
write.csv(mat, file = "12345.csv")