Divide each data frame row by vector in R

前端 未结 5 797
逝去的感伤
逝去的感伤 2020-12-15 18:54

I\'m trying to divide each number within a data frame with 16 columns by a specific number for each column. The numbers are stored as a data frame with 1-16 corresponding to

5条回答
  •  别那么骄傲
    2020-12-15 19:24

    Just for variety, you could also use mapply

    mx <- structure(list(X131.478.1 = c(4L, 93L, 123L), X131.478.2 = c(2L, 
    73L, 103L), X131.NSC.1 = c(2L, 88L, 96L), X131.NSC.2 = c(6L, 
    86L, 128L), X166.478.1 = c(7L, 58L, 46L), X166.478.2 = c(6L, 
    65L, 57L)), .Names = c("X131.478.1", "X131.478.2", "X131.NSC.1", 
    "X131.NSC.2", "X166.478.1", "X166.478.2"), class = "data.frame", row.names = c("1/2-SBSRNA4", 
    "A1BG", "A1BG-AS1"))
    
    sf <- structure(list(V1 = c(1.066088, 0.9104053, 0.8642545, 0.9611866, 
    0.9711406, 1.0560121)), .Names = "V1", row.names = c("X131.478.1", 
    "X131.478.2", "X131.NSC.1", "X131.NSC.2", "X166.478.1", "X166.478.2"
    ), class = "data.frame")
    
    
    mapply(function(x, y) x * y, mx, t(sf))
    
    
        X131.478.1 X131.478.2 X131.NSC.1 X131.NSC.2 X166.478.1 X166.478.2
    [1,]   4.264352   1.820811   1.728509    5.76712   6.797984   6.336073
    [2,]  99.146184  66.459587  76.054396   82.66205  56.326155  68.640787
    [3,] 131.128824  93.771746  82.968432  123.03188  44.672468  60.192690
    

    But for this I think Josh's answer is better... and Gavin's is even better!

提交回复
热议问题