将 R 中两个不同 table 的值相乘
Multiply value from two different table in R
我有两个从矩阵转换而来的表格:
Table 1:
Column1 Column2 Value
1 A 3
1 B 4
1 C 5
2 A 1
2 B 2
2 C 3
Table 2
Column1 Column2 Value
1 C 5
2 C 1
2 B 2
如果这两个表具有相同的标准,我想将它们的值相乘。例如:
If [Table1[Column1] == Table2[Column1] AND Table1[Column2]==Table2[Column2]
THEN Table1[Value] <- Table1[Value]*Table2[Value]
预期输出:
Table 1:
Column1 Column2 Value
1 A 3
1 B 4
1 C 5*5 - from table 2
2 A 1
2 B 2*2 from table 2
2 C 3*1 - from table 2
我试了几天创建脚本,但遇到了很多问题。
我们可以做一个连接然后做乘法
library(data.table)
setDT(Table1)[Table2, Value := Value * i.Value, on = .(Column1, Column2)]
Table1
# Column1 Column2 Value
#1: 1 A 3
#2: 1 B 4
#3: 1 C 25
#4: 2 A 1
#5: 2 B 4
#6: 2 C 3
注意:该解决方案就地赋值,速度非常快
数据
Table1 <- structure(list(Column1 = c(1L, 1L, 1L, 2L, 2L, 2L), Column2 = c("A",
"B", "C", "A", "B", "C"), Value = c(3L, 4L, 5L, 1L, 2L, 3L)), .Names = c("Column1",
"Column2", "Value"), class = "data.frame", row.names = c(NA,
-6L))
Table2 <- structure(list(Column1 = c(1L, 2L, 2L), Column2 = c("C", "C",
"B"), Value = c(5L, 1L, 2L)), .Names = c("Column1", "Column2",
"Value"), class = "data.frame", row.names = c(NA, -3L))
先合并,再相乘
names(table2)[3] <- 'Value2'
table3 <- merge(table1, table2, all.x = TRUE)
table3$Value <- with(table3, ifelse(is.na(Value2), Value, Value * Value2))
我有两个从矩阵转换而来的表格:
Table 1:
Column1 Column2 Value
1 A 3
1 B 4
1 C 5
2 A 1
2 B 2
2 C 3
Table 2
Column1 Column2 Value
1 C 5
2 C 1
2 B 2
如果这两个表具有相同的标准,我想将它们的值相乘。例如:
If [Table1[Column1] == Table2[Column1] AND Table1[Column2]==Table2[Column2]
THEN Table1[Value] <- Table1[Value]*Table2[Value]
预期输出:
Table 1:
Column1 Column2 Value
1 A 3
1 B 4
1 C 5*5 - from table 2
2 A 1
2 B 2*2 from table 2
2 C 3*1 - from table 2
我试了几天创建脚本,但遇到了很多问题。
我们可以做一个连接然后做乘法
library(data.table)
setDT(Table1)[Table2, Value := Value * i.Value, on = .(Column1, Column2)]
Table1
# Column1 Column2 Value
#1: 1 A 3
#2: 1 B 4
#3: 1 C 25
#4: 2 A 1
#5: 2 B 4
#6: 2 C 3
注意:该解决方案就地赋值,速度非常快
数据
Table1 <- structure(list(Column1 = c(1L, 1L, 1L, 2L, 2L, 2L), Column2 = c("A",
"B", "C", "A", "B", "C"), Value = c(3L, 4L, 5L, 1L, 2L, 3L)), .Names = c("Column1",
"Column2", "Value"), class = "data.frame", row.names = c(NA,
-6L))
Table2 <- structure(list(Column1 = c(1L, 2L, 2L), Column2 = c("C", "C",
"B"), Value = c(5L, 1L, 2L)), .Names = c("Column1", "Column2",
"Value"), class = "data.frame", row.names = c(NA, -3L))
先合并,再相乘
names(table2)[3] <- 'Value2'
table3 <- merge(table1, table2, all.x = TRUE)
table3$Value <- with(table3, ifelse(is.na(Value2), Value, Value * Value2))