R 在函数中创建新的数据帧

R 在函数中创建新的数据帧,r,function,dataframe,R,Function,Dataframe,我有一个数据框(df),其中有一列日期和一列数字(1、2或3),如下所示: 我已使用拆分按日期拆分此数据框: days <- split(df, df$Date) 然而,当我尝试将其写入函数时,我只得到一行数据帧。这是我的代码: myfunction <- function(df){ One <- length(which(df$Number==1)) Two <- length(which(df$Number==2)) Three <- length(whi

我有一个数据框(df),其中有一列日期和一列数字(1、2或3),如下所示:

我已使用拆分按日期拆分此数据框:

  days <- split(df, df$Date)
然而,当我尝试将其写入函数时,我只得到一行数据帧。这是我的代码:

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)
我还尝试了append=TRUE

注意-我还没有来得及将日期添加到我的新数据框中。

使用
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")
(mat
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
(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")