【问题标题】:R Loop a function with data.frame from a listR循环使用列表中的data.frame的函数
【发布时间】:2022-01-11 19:17:01
【问题描述】:

R 新手。 我想通过几个 data.frames 运行 SVM 并自动化该过程。 我在一个列表中得到了 data.frames,但不知道如何循环它们以将所有可能的可能性都放入我的函数中。简而言之,我想摆脱代码末尾的复制和粘贴。 此外,有没有办法根据 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]])

【问题讨论】:

    标签: r list loops


    【解决方案1】:

    这样的事情怎么样:

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

    【讨论】:

      【解决方案2】:

      combn 的解决方案。函数combn 有一个参数FUN,用于将函数应用于每个组合。

      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)
      

      【讨论】:

        【解决方案3】:

        创建图的一种方法是不使用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)
          })
        

        使用for loopif 语句的其他方式

        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))
            }
          }
        }
        

        【讨论】:

        • 感谢您的意见,我想出了几种方法
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-05-11
        • 2015-10-12
        • 2022-01-03
        • 2019-12-08
        相关资源
        最近更新 更多