应用正在打印的额外内容

问题描述 投票:0回答:1

我在 R 中有一个向量,如下所示:

vec <- c('abc','def')

这是我的虚拟输入数据框:

Gen value
abc 12
def 34
abc 12
abc 13
def 1
abc 4
abc 6
ghi 23

我正在使用 sapply

vec
,如下所示:

vec <- c('abc', 'def')

sapply(vec, function(x){
    print(x)
    df_mut <- data[data$Gen == x,]
    df_nonmut <- data[data$Gen != x,]
    print(nrow(df_mut))
    print(nrow(df_nonmut))
})

这给了我以下输出

[1] "abc"
[1] 703
[1] 715
[1] "def"
[1] 251
[1] 1167
abc: 715 def: 1167

为什么我会接到电话

abc: 715 def: 1167

另外,我想将这些值添加到数据框中,使其看起来像这样:

gene    mut nonmut
abc 703 715
def 251 1167

我怎样才能实现这一目标?

r lapply sapply
1个回答
0
投票

这将获得所需的数据框:如果您想详细了解它在做什么,您可以尝试在每一步中打破管道。

## count numbers of each type
 table(data$Gen) |> 
## convert from table to data frame
      as.data.frame() |> 
## compute the complement (non-mutated)
      transform(other=nrow(data)-Freq) |> 
## assign desired column names
      setNames(c("gene", "mut", "nonmut")) |> 
## keep only focal `Gen` values
      subset(gene %in% vec)
© www.soinside.com 2019 - 2024. All rights reserved.