R帮助:将值除以通过因子产生的和 [英] R help: divide values by sum produced through factor

查看:96
本文介绍了R帮助:将值除以通过因子产生的和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将列B和C中的每个值除以列A中的因子的总和。
起始矩阵看起来像这样,但有几千行
其中A是一个因子,并且B和C包含值:

I am trying to to divide each value in columns B and C by the sum due to a factor in column A. The starting matrix could look something like this but has thousands of rows where A is a factor, and B and C contain the values:

A <- c(1,1,2,2)
B <- c(0.2, 0.3, 1, 0.5)
C <- c(0.7, 0.5, 0, 0.9)
M <- data.table(A,B,C) 

> M
     A   B   C
[1,] 1 0.2 0.7
[2,] 1 0.3 0.5
[3,] 2 1.0 0.0
[4,] 2 0.5 0.9 

这些因素可以发生任意次数。
我能够使用库data.table生成每个因子的总和:

The factors can occur any number of times. I was able to produce the sum per factor with library data.table:

library(data.table)
M.dt <- data.table(M)
M.sum <- M.dt[, lapply(.SD, sum), by = A]

> M.sum
   A   B   C
1: 1 0.5 1.2
2: 2 1.5 0.9

但不知道如何从这里继续保持表格的原始格式。

but didn't know how to go on from here to keep the original format of the table.

生成的表格应该如下所示: p>

The resulting table should look like this:

B.1 <- c(0.4, 0.6, 0.666, 0.333)
C.1 <- c(0.583, 0.416, 0, 1)
M.1 <- cbind(A, B.1, C.1)

> M.1
     A   B.1     C.1
[1,] 1 0.400 0.58333
[2,] 1 0.600 0.41666
[3,] 2 0.666 0.00000
[4,] 2 0.333 1.00000

B.1中第一个值的计算将类似于这个:
0.2 /(0.2 + 0.3)= 0.4等等,其中要添加的值由A中的因子给出。

我有一些基本的R知识,

The calculation for the first value in B.1 would go like this: 0.2/(0.2+0.3) = 0.4 and so on, where the values to add are given by the factor in A.
I have some basic knowledge of R, but despite trying hard, I do badly with matrix manipulations and loops.

推荐答案

只需用每个列的每个值除以 sum A

Simply divide each value in each column by its sum per each value in A

M[, lapply(.SD, function(x) x/sum(x)), A]
#    A         B         C
# 1: 1 0.4000000 0.5833333
# 2: 1 0.6000000 0.4166667
# 3: 2 0.6666667 0.0000000
# 4: 2 0.3333333 1.0000000

想要通过引用更新do

If you want to update by reference do

M[, c("B", "C") := lapply(.SD, function(x) x/sum(x)), A]



Or more generally

M[, names(M)[-1] := lapply(.SD, function(x) x/sum(x)), A]






$ c> dplyr junkies

library(dplyr)
M %>%
  group_by(A) %>%
  mutate_each(funs(./sum(.)))

# Source: local data table [4 x 3]
# Groups: A
# 
#   A         B         C
# 1 1 0.4000000 0.5833333
# 2 1 0.6000000 0.4166667
# 3 2 0.6666667 0.0000000
# 4 2 0.3333333 1.0000000

这篇关于R帮助:将值除以通过因子产生的和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆