美文网首页
操作矩阵每行元素| R Programming for Bioi

操作矩阵每行元素| R Programming for Bioi

作者: kkkkkkang | 来源:发表于2022-02-10 20:01 被阅读0次

    最近在看这本书:https://www.amazon.com/Programming-Bioinformatics-Chapman-Computer-Analysis/dp/1420063677
    其中有一道习题

    Write an R function that takes a matrix as input and standardizes each row
    by subtracting the median and dividing by the MAD. You might want to look
    at the functions mad and median. Next, generalize your function so that these
    are the default values, but allow the user to select other measures of the center
    and spread, should they want to use them.

    就是要把矩阵的每行元素都减去median然后除以mad值
    然后把这两个函数作为默认,允许用户自己输入函数来计算

    set.seed(123)
    a <- matrix(sample(1:20,12),ncol = 3)
    a
    f1 <- function(x) {
        median_row <- apply(x,1,median)
        mad_row <- apply(x,1,mad)
        x <- sweep(sweep(x,1,median_row),1,FUN = "/",mad_row)
        return(x)
    }
    f1(a)
    
    # generalized
    f1 <- function(x, 
                   sub_fun = "median", 
                   divid_fun = "mad") {
        median_row <- apply(x,1,sub_fun)
        mad_row <- apply(x,1,divid_fun)
        x <- sweep(sweep(x,1,median_row),1,FUN = "/",mad_row)
        return(x)
    }
    
    f1(a)
    

    用到了sweep函数

    相关文章

      网友评论

          本文标题:操作矩阵每行元素| R Programming for Bioi

          本文链接:https://www.haomeiwen.com/subject/mcfikrtx.html