【问题标题】:Use nonstandard evaluation and mutate in r dataframe with dplyr使用 dplyr 在 r 数据帧中使用非标准评估和变异
【发布时间】:2020-08-18 01:13:42
【问题描述】:

我无法弄清楚如何使用包含 R 数据框列名的字符串进行一些基本计算以变异为新列。例如,我有基线值列和其他具有治疗后时间点的列。我想为此使用列名字符串,因为我将使用指定了不同时间点的数据,并且我想要一个编程解决方案。

例如,我有这个数据框,我想我需要在下面的 mutate 行中使用一些语法,但不知道如何写右手边。我希望名为“day1_fc”和“day2_fc”的列代表 day1/baseline 和 day2/baseline 的倍数变化。

df <- data.frame(day0 = c(1,1,1),
                 day1 = c(2,3,4),
                 day2 = c(3,4,5))

baseline = 'day0'
sym_baseline <- sym(baseline)

post = c('day1', 'day2')
post1 <- post[1]
post2 <- post[2]

df %>% 
  mutate(!!paste0(post1, '_fc' := ?????),
         !!paste0(post2, '_fc') := ?????)

我希望结果看起来像:

  df <- data.frame(day0 = c(1, 0.5, 2),
                   day1 = c(2, 3, 4),
                   day2 = c(3, 4, 5),
                   day1_fc = c(2, 6, 2),
                   day2_fc = c(3, 8, 2.5))

【问题讨论】:

    标签: r dataframe dplyr non-standard-evaluation


    【解决方案1】:

    你可以使用:

    library(dplyr)
    library(rlang)
    
    df %>% 
      mutate(!!paste0(post1, '_fc') := !!sym(post[1])/!!sym_baseline,
             !!paste0(post2, '_fc') := !!sym(post[2])/!!sym_baseline)
    
    #  day0 day1 day2 day1_fc day2_fc
    #1  1.0    2    3       2     3.0
    #2  0.5    3    4       6     8.0
    #3  2.0    4    5       2     2.5
    

    post 的许多值的一般解决方案是使用 map:

    bind_cols(df, purrr::map_dfc(post, 
                 ~df %>% transmute(!!paste0(.x, '_fc') := !!sym(.x)/!!sym_baseline)))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-27
      • 2019-03-23
      • 2015-03-10
      相关资源
      最近更新 更多