Lince202
Lince202

Reputation: 143

How to create sub-dataframes setting 3 variables

I have a dataframe with 6 variables (x, y, E, freq, Perc, Rip).

library(dplyr)
library(scales)

a<-c(10,20,30,40,50,60,70,80,90,100)
b<-c(15,25,35,45,55,65,75,85,95,105)
x<-rep(a,3)
y<-rep(b,3)
E<-sample(30)
freq<-as.character(rep(c(100,200,300),10))

Perc_Points<- percent(seq(0.9,0.1,by=-0.1))

data<-data.frame(x,y,freq,E)

data1<-group_by(data,freq)

N <- 10
df <- vector("list", N)

df <- lapply(1:N, function(i)
                {  lista <- sapply(seq(0.9, 0.1, -0.1), 
                   function(pct) {sample_frac(data1, pct)}, 
                   simplify=FALSE)
                   names(lista) <- Perc_Points
                   xxxx <- bind_rows(lista, .id = "Perc")
                   df[[i]] <- xxxx
                })

df<-bind_rows(df, .id="Rip")
df<-data.frame(df)

Now i want to work with sub-dataframes of df, one for each different value of freq, Perc and Rip.

For example, a dataframe with freq= 100, Perc= 90%, Rip=1, another with freq= 100, Perc= 90%, Rip=2, etc...

I try with group_by(df, Perc, freq, Rip), but there is a problem: i have to apply krige function to each of this sub-dataframe, and this function doesn't work with grouped_df. How can I do that?

Upvotes: 0

Views: 57

Answers (1)

akrun
akrun

Reputation: 887531

We can use split

lst <- split(df, list(df$Rip, df$Perc, df$freq), drop=TRUE)

and then loop over the list elements with lapply and apply the function

Or if we need to work with dplyr, use do

df %>%
  group_by(Rip, Perc, freq) %>%
  do(data.frame(krigeFunc(arg1, arg2,..))) #not clear about the function

Upvotes: 2

Related Questions