使用条件语句的算术运算

Arithmetic operation using a conditional statement

我需要编写一个函数,在满足两个条件的情况下将一列除以矩阵的一个元素。这两个条件改变也改变了矩阵元素。

foo <- c('A', 'B', 'C', 'D', 'F', 'G')
phi <- c('Z1', 'Z1', 'X3', 'W4', 'V5', 'W4')
tal <- c('1-2', '3-4', '5-6', '7-8', '9-10', '11-12')
n <- c(324, 872, 163, 953, 453, 943)
df <- data.frame(foo, phi, tal, n)

mtx <- c(5983, 4079, 4253, 3516, 3452, 2519, 10079, 3083, 1998, 3115, 3545, 327790, 6847, 2583, 2193, 2221, 3557, 5031, 866, 3685, 3452, 2519, 10079, 3083, 1998)
mtx <- matrix(mtx, 6, 6, dimnames = list(c('Z1', 'Y2', 'X3', 'W4', 'V5', 'U6'), c('1-2', '3-4', '5-6', '7-8', '9-10', '11-12')))

我需要这样写:

df$P <- ifelse(df$phi=="Z1" & df$tal == "1-2", df$n/mtx[1,1],
     df$phi=="Z1" & df$tal == "3-4", df$n/mtx[1,2],
     df$phi=="Y2" & df$tal == "1-2", df$n/mtx[2,1])

我知道 ifelse 函数本身不足以满足我的需要。有人能找到解决方案吗?非常感谢

在 LHS 和 RHS 上使用 within 和相同的子集。

df <- within(df, {
  P <- NA
  P[phi == "Z1" & tal == "1-2"] <- n[phi == "Z1" & tal == "1-2"]/mtx[1, 1]
  P[phi == "Z1" & tal == "3-4"] <- n[phi == "Z1" & tal == "3-4"]/mtx[1, 2]
  P[phi == "Y2" & tal == "1-2"] <- n[phi == "Y2" & tal == "1-2"]/mtx[2, 1]
})
df
#   foo phi   tal   n          P
# 1   A  Z1   1-2 324 0.05415343
# 2   B  Z1   3-4 872 0.14574628
# 3   C  X3   5-6 163         NA
# 4   D  W4   7-8 953         NA
# 5   F  V5  9-10 453         NA
# 6   G  W4 11-12 943         NA