繁体   English   中英

如何在不使用硬编码列名的情况下使用dplyr将函数逐行应用到数据帧中

[英]How to apply function row-by-row into a data frame using dplyr without hardcoding the column names

我有以下数据框:

dat <- structure(list(setosa = c(50L, 0L, 0L), versicolor = c(0L, 11L, 
39L), virginica = c(0L, 36L, 14L)), .Names = c("setosa", "versicolor", 
"virginica"), row.names = c("1", "2", "3"), class = "data.frame")

dat
#>   setosa versicolor virginica
#> 1     50          0         0
#> 2      0         11        36
#> 3      0         39        14

这是我用来通过将列名称硬编码到其中来计算得分的当前代码:

library(dplyrj)
dat %>% 
  rowwise() %>% 
  # here I hard code the column names into the score
  mutate(score = max(c(setosa,versicolor, virginica)/ sum(c(setosa, versicolor, virginica))))

产生:

# A tibble: 3 x 4
  setosa versicolor virginica score
   <int>      <int>     <int> <dbl>
1     50          0         0 1.00 
2      0         11        36 0.766
3      0         39        14 0.736

我想做的是计算每个分数,但不对列名进行硬编码。

如何实现呢?

简洁的base R选项为

dat$score <- do.call(pmax, dat)/rowSums(dat)

tidyverse我们可以做

library(tidyverse)
dat %>% 
    mutate(score = do.call(pmax, .)/reduce(., `+`))
#   setosa versicolor virginica     score
#1     50          0         0 1.0000000
#2      0         11        36 0.7659574
#3      0         39        14 0.7358491

使用unquote拼接运算符!!! , 你可以做:

> library(tidyverse)
> psum <- function(...) reduce(list(...), `+` )
> mutate( dat, core = pmax(!!!syms(names(dat))) / psum(!!!syms(names(dat))) )
  setosa versicolor virginica      core
1     50          0         0 1.0000000
2      0         11        36 0.7659574
3      0         39        14 0.7358491

这可以通过为您生成呼叫来实现,即

> rlang::qq_show( mutate( dat, core = pmax(!!!syms(names(dat))) / psum(!!!syms(names(dat))) ) )
mutate(dat, core = pmax(setosa, versicolor, virginica) / 
                   psum(setosa, versicolor, virginica)
)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM