以给定字符串结尾的列的Pmax [英] Pmax of columns ending with a given string

查看:55
本文介绍了以给定字符串结尾的列的Pmax的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对给定行有条件地更改一个新列,该列表示以"_n"结尾的列的 pmax().我知道我可以通过显式指定列名来做到这一点,但是我更希望这是调用 ends_with()或类似名称的结果.

I would like to conditionally mutate a new column representing the pmax() of columns ending with "_n" for a given row. I know I can do this by explicitly specifying the column names, but I would prefer to have this be the result of a call to ends_with() or similar.

我尝试了 mutate_at()和普通的 mutate().我的一般想法是,我需要将 vars(ends_with("_ n"))传递给某些东西,但是我只是缺少了一些东西.

I have tried mutate_at() and plain mutate(). My general thought is that I need to pass a vars(ends_with("_n")) to something, but I'm just missing that something.

谢谢.

library(dplyr)
library(tidyr)

mtcars %>%
  group_by(vs, gear) %>% 
  summarize(mean = mean(disp),
            sd = sd(disp),
            n = n()) %>% 
  mutate_if(is.double, round, 1) %>% 
  mutate(mean_sd = paste0(mean, " (", sd, ")")) %>% 
  select(-mean, -sd) %>%
  group_by(vs, gear) %>% 
  nest(n, mean_sd, .key = "summary") %>% 
  spread(key = vs, value = summary) %>% 
  unnest(`0`, `1`, .sep = "_")

   gear `0_n` `0_mean_sd`   `1_n` `1_mean_sd` 
  <dbl> <int> <chr>         <int> <chr>       
1     3    12 357.6 (71.8)      3 201 (72)    
2     4     2 160 (0)          10 115.6 (38.5)
3     5     4 229.3 (113.9)     1 95.1 (NA)   

两个答案都值得赞赏.干杯!

edit: both answers are much appreciated. Cheers!

推荐答案

这是使用unquote-splice运算符的一种方法.我们可以选择要比较的列,然后将它们作为向量拼接到 pmax 中:

Here's one way using the unquote-splice operator. We can select columns that we want to compare and then splice them as vectors into pmax:

library(tidyverse)
tbl <- structure(list(gear = c(3, 4, 5), `0_n` = c(12L, 2L, 4L), `0_mean_sd` = c("357.6 (71.8)", "160 (0)", "229.3 (113.9)"), `1_n` = c(3L, 10L, 1L), `1_mean_sd` = c("201 (72)", "115.6 (38.5)", "95.1 (NA)")), row.names = c(NA, -3L), class = c("tbl_df", "tbl", "data.frame"))
tbl %>%
  mutate(pmax = pmax(!!!select(., ends_with("_n"))))
#> # A tibble: 3 x 6
#>    gear `0_n` `0_mean_sd`   `1_n` `1_mean_sd`   pmax
#>   <dbl> <int> <chr>         <int> <chr>        <int>
#> 1     3    12 357.6 (71.8)      3 201 (72)        12
#> 2     4     2 160 (0)          10 115.6 (38.5)    10
#> 3     5     4 229.3 (113.9)     1 95.1 (NA)        4

reprex软件包(v0.2.1)于2019-04-23创建sup>

Created on 2019-04-23 by the reprex package (v0.2.1)

这篇关于以给定字符串结尾的列的Pmax的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆