0

I have a data frame (df) with a column of dates and a column of numbers (either 1, 2 or 3) like so:

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

I have split this data frame by date using split:

  days <- split(df, df$Date)

I then want to apply a function to each day in the split data frame to count how many times "1", "2" or "3" occurs for each day. This is what I have:

myfunction <- function(df){
One <- length(which(df$Number==1))
Two <- length(which(df$Number==2))
Three <- length(which(df$Number=="NA"))
}

lapply(days, myfunction)

If I use e.g. print(One) at the end of this function it will print the amount of times 1 appears for each day. However, I want to create a new data frame with the date and the number of times each number occurs, which looks like so:

Date          1    2    3

01/01/2014    2    1    1
02/01/2014    0    3    1
03/01/2014    1    0    1

When I try to write this into my function however, I only get one line of the data frame. This is the code I have:

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)

Here are the errors I am receiving:

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

I have also tried with append=TRUE.

NB - I haven't got around to adding the dates into my new data frame yet.

1 Answer 1

1

Using xtabs (or table) will make your life easier here.

(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")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.