代码之家  ›  专栏  ›  技术社区  ›  neuron

行错误“x”必须是数字

r
  •  0
  • neuron  · 技术社区  · 7 年前

    rowSums 但我有一些问题。以下是列名列表:

    colnames(No_Low_No_Intergenic_snpeff)
    
    "CHROM" "POS"   "REF"   "ALT"   "QUAL"  "ANN.ALLELE"    "ANN.EFFECT"
    "ANN.IMPACT"    "ANN.GENE"  "ANN.GENEID"    "ANN.FEATURE"   "ANN.FEATUREID"
    "ANN.HGVS_C"    "ANN.HGVS_P"    "ANN.ERRORS"    "GEN.C02141.GT" "GEN.C00611.GT"
    "GEN.C00633.GT" "GEN.C00634.GT" "GEN.C00644.GT" "GEN.C00647.GT" "GEN.C00648.GT"
    "GEN.C00649.GT" "GEN.C00650.GT" "GEN.C00653.GT" "GEN.C00655.GT" "GEN.C00656.GT"
    "GEN.C00657.GT" "GEN.C00659.GT" "GEN.C00682.GT" "GEN.C00705.GT" "GEN.C00707.GT"
    "GEN.C00720.GT" "GEN.C00783.GT" "GEN.C01431.GT" "GEN.C01944.GT" "GEN.C01943.GT"
    "GEN.C01403.GT" "GEN.C01158.GT" "GEN.C01157.GT" "GEN.C01156.GT" "GEN.C01033.GT"
    "GEN.C00736.GT" "GEN.C00639.GT" "GEN.C99686.GT"
    

    GEN.Cxxxxx.GT 这些列中的所有值都在0-2之间。我尝试对第20:29列和第45列求和,然后将值放入名为 controls

    No_Low_No_Intergenic_snpeff.scores$controls <- rowSums(No_Low_No_Intergenic_snpeff.scores[,20:29,45])
    

    但当我尝试运行该命令时,会得到以下错误:

    Error in rowSums(No_Low_No_Intergenic_snpeff.scores[, 20:29, 45]) : 'x' must be numeric
    

    str(No_Low_No_Intergenic_snpeff.scores)
    
    'data.frame':   1000 obs. of 11 variables:
    $ GEN.C00644.GT: Factor w/ 3 levels "0","1","2": 3 1 1 3 3 3 2 1 3 1 ...
    $ GEN.C00647.GT: Factor w/ 3 levels "0","1","2": 3 1 3 3 2 2 2 1 2 1 ...
    $ GEN.C00648.GT: Factor w/ 3 levels "0","1","2": 3 1 1 3 3 3 1 1 2 1 ...
    $ GEN.C00649.GT: Factor w/ 3 levels "0","1","2": 3 1 1 3 2 2 2 1 2 1 ...
    ...
    
    1 回复  |  直到 7 年前
        1
  •  3
  •   divibisan    7 年前

    因为值不是 numeric str

    GEN.C00650.GT: Factor w/ 3 levels "0","1","2": 3 1 3 3 3 3 1 1 3 1 ... 
    

    这些是班级 factor 数字 as.numeric

    如果可以再次从文件导入数据,则可以使用 stringsAsFactors = FALSE

    最简单的方法是使用 sapply

    rowSums(sapply(No_Low_No_Intergenic_snpeff.scores[, c(20:29, 45)], as.numeric))
    

    作为数字 rowSums

    泰迪弗斯

    mutate_if dplyr 将所有因子变量转换为数字。

    library(dplyr)
    
    No_Low_No_Intergenic_snpeff.scores <- No_Low_No_Intergenic_snpeff.scores %>%
        mutate_if(is.factor, as.numeric)
    
    rowSums(No_Low_No_Intergenic_snpeff.scores[, c(20:29, 45)])
    

    mutate_at ?select 要查看所有不同的方式,可以选择列。甚至可以将正则表达式用于 matches

    No_Low_No_Intergenic_snpeff.scores <- No_Low_No_Intergenic_snpeff.scores %>%
        mutate_at(vars(matches('GEN.C\\d{5}.GT')), funs(as.numeric))
    

    这将应用该功能 GEN.C\\d{5}.GT ,在哪里 \\d{5}