首页 文章

如何捕获元素向量,以便它们被R dplyr函数读取?

提问于
浏览
1

我正在尝试使用dplyr包,但我遇到了处理变量的问题 .

假设我有一个简化数据帧

my.data <- as.data.frame(matrix(NA), ncol=4, nrow=6)
my.data <- as.data.frame(cbind(c("d6", "d7", "d8", "d9", "da", "db"), c(rep("C200", 2), rep("C400", 4)), c(rep("a",5), "b"), c("c", rep("a", 5))))
colnames(my.data) <- c("snp", "gene", "ind1", "ind2")

我首先用group_by计算每个基因的snp数:

new.data <- my.data %>% group_by(gene) %>% mutate(count = n())

但是我希望每个列的基因百分比得到字符串出现:

new.data %>% group_by(gene) %>% filter(grepl("a", ind1)) %>% dplyr::mutate(perc.a.ind1 = n()/count*100)
new.data %>% group_by(gene) %>% filter(grepl("a", ind2)) %>% dplyr::mutate(perc.a.ind2 = n()/count*100)

它工作正常 . 问题是我有很多人,我需要自动化它 . 所以我创建了一个名称向量并在for循环中运行我的函数(我知道循环不是最好的,我很乐意升级到应用版本或其他东西)

ind.vec <- colnames(my.data[,3:4])
for (i in 1:length(ind.vec){
new.data %>% group_by(gene) %>% filter(grepl("a", ind.vec[i])) %>% mutate(percent = n()/count*100)

}

我最后得到一个空的tibble,就像我的ind.vec中没有一个元素被识别一样 .

我读了小插曲https://cran.r-project.org/web/packages/dplyr/vignettes/programming.html,这让我觉得我已经发现了问题,但是我很难理解它,也无法使它与我的数据一起工作 .

我做了一些试验

ind.vec <- quote(colnames(my.data[,3:4]))
new.data %>% group_by(gene) %>% filter(grepl("a", !!(ind.vec[i]))) %>% mutate(percent = n()/count*100)

如何使dplyr识别向量元素?

你可以帮忙吗?

2 回答

  • 0

    我建议你使用tidyr :: gather .

    library(tidyverse)
    # or library(dplyr);library(tidyr)
    
    my.data %>% 
      group_by(gene) %>% 
      mutate(count = n()) %>% 
      gather(ind, string, ind1, ind2 ) %>% 
      filter(string == "a") %>% 
      group_by(gene, ind, string) %>% 
      mutate(
        n_string = n(),
        freq = n_string /  count * 100 ) 
    
    # A tibble: 10 x 7
    # Groups:   gene, ind, string [4]
    #      snp   gene count   ind string n_string  freq
    #    <fctr> <fctr> <int> <chr>  <chr>    <int> <dbl>
    # 1     d6   C200     2  ind1      a        2   100
    # 2     d7   C200     2  ind1      a        2   100
    # 3     d8   C400     4  ind1      a        3    75
    # 4     d9   C400     4  ind1      a        3    75
    # 5     da   C400     4  ind1      a        3    75
    # 6     d7   C200     2  ind2      a        1    50
    # 7     d8   C400     4  ind2      a        4   100
    # 8     d9   C400     4  ind2      a        4   100
    # 9     da   C400     4  ind2      a        4   100
    #10     db   C400     4  ind2      a        4   100
    

    我出于某种原因收到警告,但结果与您提供的结果相同 .

  • 0

    @SollanoRabeloBraga,非常感谢你!它解决了我的问题 . 我修改了聚集功能以包含更多个体 gather(ind, string, ind1:ind5) 然后我做了

    new.data <- test[!duplicated(new.data[, c("gene", "ind", "freq")]),]
    
    new.data <- cast(test2, gene ~ ind)
    

    擦亮我的结果 .

相关问题