I'm trying to write a function which will subset a dataframe for me, according to different lengths of time (number of months); and create a list of new dataframes which are all slightly different subsets. I want to be able to apply this function to any data.
Here is an example of what I'm trying to do.
month <- c(0:35)
product<- c(112:147)
index <- rnorm(36)
originaldata <- data.frame(month, product, index)
sset <- function(df, time, length, windows) {
#Create the subset rule
subfun <- function(x,y,z) { x[x[[y]] >= z & x[[y]] <= z+length-1,] }
#Apply this rule to dataframe
regdfs <- lapply(1:windows,
function(j) {subfun(x = df, y = time, z = j - 1) })
}
#Apply sset function to create dataframe subsets
camsets <- sset(df = originaldata, time = originaldata$month, length = 13, windows = 24)
When I run this code, I get a variety of error messages.
This is the link to my original question, which was helpfully answered (thanks Carl), Create a list of a list of dataframes, by subsetting a list of dataframes in R . This time I'm trying to write a function to do this, and I'm probably doing something stupid.
Any help much appreciated, thanks.
Error in .subset2(x, i, exact = exact) : attempt to select less than one element in integerOneIndex. Thanks for your help.x[[y]]can only retrieve a single column of a data.frame, but you are passing a vector iny; perhaps you meanx[y,]? Second,yis 0-based, but vectors in R are 1-based, so you are likely not getting back what you want.In Ops.factor(left, right) : ‘<=’ not meaningful for factors. Any ideas? Thanks.