Home > Mobile >  R Loop a function with data.frame from a list
R Loop a function with data.frame from a list

Time:12-07

New to R. I want to run a SVM through several data.frames and automize the process. I got the data.frames in a list, but didn't know how to loop them to get every possible eventuality into my function. In short, i want to get rid of the copy&paste at the end of my code. Furthermore, is there a way to label my plot depending on the ingoing data of myfunction?

df1<-iris
df2<-iris
df2$Petal.Width = df2$Petal.Width 2
df3<-iris
df3$Petal.Width = df3$Petal.Width-2
df4<-iris
df4$Petal.Width = df4$Petal.Width-5
Werte <- list(df1,df2,df3,df4)

new_function <- function(V1, V2){
m2<-data.frame(V1$Petal.Width, V2$Petal.Width)
plot(m2)
}

new_function(V1=Werte[[1]],V2=Werte[[2]])
new_function(V1=Werte[[1]],V2=Werte[[3]])
new_function(V1=Werte[[1]],V2=Werte[[4]])
new_function(V1=Werte[[2]],V2=Werte[[3]])
new_function(V1=Werte[[2]],V2=Werte[[4]])
new_function(V1=Werte[[3]],V2=Werte[[4]])

CodePudding user response:

How about something like this:

combs <- combn(length(Werte), 2)
lapply(1:ncol(combs), function(i){
  new_function(V1=Werte[[combs[1,i]]], 
               V2=Werte[[combs[2,i]]])})

CodePudding user response:

A solution with combn. Function combn has an argument FUN, meant to apply a function to each combination.

new_function <- function(V1, V2){
  m2 <- data.frame(x = V1$Petal.Width, y = V2$Petal.Width)
  plot(y ~ x, m2)
}

combn(length(Werte), 2, function(k) {
  new_function(Werte[[ k[1] ]], Werte[[ k[2] ]])
}, simplify = FALSE)

CodePudding user response:

One way to create the plots will be without using loop

new_function <- function(data, x1, x2){
  V1 <- data[[x1]]
  V2 <- data[[x2]]
  m2 <- data.frame(V1$Petal.Width, V2$Petal.Width)
  plot(m2, main = paste('Plot of dataframe', x1, 'and', x2))
}

Diff_Combs <- combn(1:length(Werte), m = 2)

apply(Diff_Combs, 2, function(x) {
  x1 <- x[1]
  x2 <- x[2]
  y <- new_function(Werte, x1, x2)
  return(y)
  })

Other way using a for loop along with an if statement

for(i in 1:length(Werte)) {
  for(j in 1:length(Werte)) {
    if (i < j) {
      plot(Werte[[i]]$Petal.Width, Werte[[j]]$Petal.Width, 
           main = paste('Plot of dataframe', i, 'and', j))
    }
  }
}
  • Related