【问题标题】:How to divide the values of multiple columns by the values of a single column of a dataset in R如何将多个列的值除以R中数据集的单个列的值
【发布时间】:2022-12-05 07:14:10
【问题描述】:

我有一个类似于下面的数据集,我正在向您展示

gene_name gene_length value1 value2 value3
NameA 1070 100 300 600
NameB 110 200 600 1200

我的目标是使用除法结果创建新列列值 1、值 2、值 3... 中的值...值-ngene_length 列中的值.

是这样的:

gene_name gene_length value1 value2 value3 value1_result value2_result value3_result
NameA 1070 100 300 600 0.0934 0.2803 0.5607
NameB 110 200 600 1200 1.8181 5.4545 10.9090

我可以用很少的列和行在 R 中应用几个 mutate 函数,但问题是我的数据集有超过 5 万行和 21 列。

如何使用 tidyverse 更有效地完成这项任务?

我读过我可以将 mutate 函数与 across 函数结合使用,但是我无法让它们一起工作。

desired_df <- df %>% 
  mutate(across(.cols = 3:21, # 21 because of the 21 columns i have in my dataframe
                # I need to specify a function to perform the division in the columns i want 
                # but i dont know how
                .names = '{col}_value')) # names of new columns

【问题讨论】:

    标签: r tidyverse


    【解决方案1】:

    循环 across 'value' 列,创建一个 lambda 函数 (~) 将列 (.x) 除以 'gene_length' 并修改 .names 以创建以 _result 作为后缀的新列

    library(dplyr)
    desired_df <- df %>% 
      mutate(across(.cols = starts_with("value"), ~ .x/gene_length,
                    .names = '{.col}_result')) 
    

    【讨论】:

      猜你喜欢
      • 2022-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-24
      • 1970-01-01
      • 2021-07-10
      • 1970-01-01
      相关资源
      最近更新 更多