【问题标题】:How does one access the piped data.frame in dplyr::funs?如何访问 dplyr::funs 中的管道 data.frame?
【发布时间】:2016-12-05 09:59:24
【问题描述】:

例如,如果访问者是..,这将起作用:

iris %>% 
  select_if(is.numeric) %>% 
  # `..` here refers to the object generated thus far. 
  # `.` refers to the column being acted on.
  mutate_all(funs(./sum(..)))

【问题讨论】:

  • 我不相信你可以访问管道,虽然你可以直接打电话给iris
  • @kennyB 请说明您的要求。
  • 所以你想用一列中的每个元素除以该列的总和,或者一列中的每个元素除以所有列的总和?
  • @steveb,所有列的总和。

标签: r dplyr


【解决方案1】:

如果你想取列总和,你可以

iris %>% 
  select_if(is.numeric) %>% 
  mutate_all(funs(./sum(.)))

如果要取总和,可以将其存储为另一列

iris %>% select_if(is.numeric) %>% 
  mutate(totsum = sum(.)) %>%
  mutate_at(vars(-totsum), funs(./totsum))

我不认为将 dplyr 用于此类非列或行分组操作有什么好处。

【讨论】:

  • 我认为他们想要的是 DF 的总和,而不是列的总和。他们应该改用矩阵。
  • 同意。或者他们可以只存储iris %>% select_if(is.numeric) %>% sum() 的结果。
【解决方案2】:

我们可以使用data.table

 library(data.table)
 as.data.table(iris)[, lapply(.SD, function(x) if(is.numeric(x)) x/sum(x)) else NULL)]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-14
    • 2017-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多