【问题标题】:Apply a function to each element of each dataframe in a list将函数应用于列表中每个数据框的每个元素
【发布时间】:2019-09-26 23:33:00
【问题描述】:

我想将函数元素应用于数据框列表。我可以应用一个简单的函数,但不能应用更复杂的函数,因为我不确定如何引用参数。

我可以对数据框执行以下操作:

df1 <- data.frame(
  A = c(1, 2),
  B = c(1, 3)
)
centered <- apply(df1, 2, function(x) x - mean(x)) 
scaled <- apply(centered, 2, function(x) x/sqrt(sd(x)))

然后我创建一个包含两个数据框的列表(它们的行数相同但列数不同):

df1 <- data.frame(
      A = c(1, 2),
      B = c(1, 3))
 df2 <- data.frame(
      A = c(1, 2, 3, 4),
      B = c(1, 2, 3, 4))
 l=list(df1,df2)

我了解到,mapply 似乎可以做我想做的事。但是,如何应用上面的动作?这是函数(x,y)的映射。我想从上面应用操作centeredscaled

l_output <- mapply(function(x,y) x*y, x = 2, y = list, SIMPLIFY = FALSE)

【问题讨论】:

  • 您希望输出的结构类型是什么?
  • 我想要一个数据帧列表,与输入相同,但应用了缩放函数。 Ronak 的回答有效!

标签: r list function


【解决方案1】:

使用lapply 应用相同的功能。这将居中和缩放功能一起应用。

lapply(l, function(y) apply(y, 2, function(x) {
        x = x - mean(x)
        x/sqrt(sd(x))
}))

#[[1]]
#              A          B
#[1,] -0.5946036 -0.8408964
#[2,]  0.5946036  0.8408964

#[[2]]
#              A          B
#[1,] -1.3201676 -1.3201676
#[2,] -0.4400559 -0.4400559
#[3,]  0.4400559  0.4400559
#[4,]  1.3201676  1.3201676

如果你想要它们分开

centered <- lapply(l, function(y) apply(y, 2, function(x) x - mean(x)))
scaled <- lapply(centered, function(y) apply(y, 2, function(x) x/sqrt(sd(x))))

【讨论】:

    【解决方案2】:

    一个选项是使用purrr::map 迭代数据帧,使用dplyr::mutate_all 将函数应用于每个数据帧中的所有列。

    purrr::map(l, function(d) {
      dplyr::mutate_all(d, function(x) {
        x <- x - mean(x)
        x / sqrt( sd(x) )
      })
    })
    #> [[1]]
    #>            A          B
    #> 1 -0.5946036 -0.8408964
    #> 2  0.5946036  0.8408964
    #> 
    #> [[2]]
    #>            A          B
    #> 1 -1.3201676 -1.3201676
    #> 2 -0.4400559 -0.4400559
    #> 3  0.4400559  0.4400559
    #> 4  1.3201676  1.3201676
    

    或者,如果您声明该函数,您可以在一行中完成:

    center_and_scale <- function(x) {
      x <- x - mean(x)
      x / sqrt( sd(x) )
    }
    
    purrr::map(l, dplyr::mutate_all, center_and_scale)
    # same output
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-24
      • 2020-12-31
      • 2022-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多