【问题标题】:Create a new variable which is the fold change of one row over another row and do this for multiple variables创建一个新变量,它是一行相对于另一行的倍数变化,并对多个变量执行此操作
【发布时间】:2019-06-03 16:17:16
【问题描述】:

我有样本运行并生成了 8 个变量的数据。每个样本都有一个“NIL”运行,以及同一样本的 3 个其他“版本”(有时是 4 个或 5 个)。我需要的是,创建 8 个新变量,这将是每个版本的样本与该样本的 NIL 的倍数变化。

要对所有变量运行它,我知道我需要使用 mutate_at(.funs=funs(FUNCTION HERE), .vars=var1:var8) 之类的东西。但是,我无法弄清楚要使用什么功能。

x<-c(50,25,10,5)
y<-c(100,50,25,10)
z<-c(50,25,10,5)

sample<-c("a","a","a","a") 
sample_type<-c("a_bcg","a_esf","a_hiv","a_nil")
## sample_type column is the one which would serve as a reference for 
## me of how these "a"s are different from each other but for 
## calculation purposes we can just group by sample  
test<-as.tibble(cbind(x,y,z,sample))
test<-test%>%
  modify_at(c(1,2,3),as.numeric)

test%>%
  group_by(sample)%>% ## since there'd be more groups 
  mutate_at(.funs = funs(./slice(n)),.vars = (1:3))

这失败了 mutate_impl(.data, dots) 中的错误: 评估错误:没有适用于 'slice_' 的方法应用于 “c('double', 'numeric')”类的对象。

我需要创建一个函数,该函数获取一列的每一行的值并将其与特定行(在该子组中)相除 - 该行中有一个“nil”,因此我可以使它nil 样本可能始终是组中的第一个或最后一个。

The expected would look like this 

x     y     z     sample   x_1   y_1   z_1
  <chr> <chr> <chr> <chr>  <dbl> <dbl> <dbl>
1 50    100   50    a         10  10      10
2 25    50    25    b          5   5       5
3 10    25    10    c          2   2.5     2
4 5     10    5     nil        1   1       1

【问题讨论】:

    标签: r dplyr slice tidyverse


    【解决方案1】:

    我在您的数据中创建了一个引用 ref 列,它指示要划分的“nil”行。然后,您的预期结果将由以下方式给出:

    library(tidyverse)
    
    x <- c(50,25,10,5)
    y <- c(100,50,25,10)
    z <- c(50,25,10,5)
    
    sample <- c("a","a","a","a") 
    sample_type <- c("a_bcg","a_esf","a_hiv","a_nil")
    ## sample_type column is the one which would serve as a reference for 
    ## me of how these "a"s are different from each other but for 
    ## calculation purposes we can just group by sample  
    
    ref <- c(0, 0, 0, 1)
    test <- as.tibble(cbind(x,y,z,sample, ref))
    test <- test%>%
              modify_at(c(1,2,3),as.numeric)
    
    test%>%
      group_by(sample)%>% ## since there'd be more groups 
      mutate_at(.funs = funs( `1` = . / .[ref == 1]), .vars = (1:3))
    

    我已使您的代码尽可能接近您发布它的方式。

    【讨论】:

    • 太棒了。我想出了一个稍微不同的版本,它对 ref 进行了排序,使得 1 始终是组中的第一行并使用“.[1]”。但是您的解决方案要灵活得多。
    猜你喜欢
    • 2020-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多