简体   繁体   English

通过匹配命名数字将 R 数据帧的行相乘

[英]Multiply rows of R dataframe by matching named numeric

How can you selectively multiple a row in a dataframe by the corresponding number in a named numeric?如何通过命名数字中的相应数字有选择地将数据框中的一行多倍?

## Create DataFrame
d <- data.frame(a=c(1,1,2), b=c(2,2,1), c=c(3,0,1))
rownames(d) = c("X", "Y", "Z")

## Create Named Numeric
named_numeric = c(2,1,3)
names(named_numeric) = c("X", "Y", "Z")
named_numeric

All values in the first row of the dataframe ("X": 1,2,3) would by multiplied by the value of "X" in the named numeric (2) in this case.在这种情况下,数据帧第一行中的所有值 ("X": 1,2,3) 将乘以命名数字 (2) 中的 "X" 值。 The result of the first row would be "X": 2,4,6.第一行的结果将是“X”:2,4,6。

expected_output = data.frame(a=c(2,1,6), b=c(4,2,3), c=c(6,0,3))
rownames(expected_output) = c("X", "Y", "Z")

We can just do我们只能做

out <- d * named_numeric
identical(expected_output, out)
#[1] TRUE

if the names of named_numeric is not aligned with the row names, then reorder one of them and multiply如果named_numeric的名称与行名称不对齐,则重新排序其中之一并相乘

d * named_numeric[row.names(d)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM