【发布时间】:2023-03-10 14:40:02
【问题描述】:
如果满足两个条件,我需要编写一个函数来将列除以矩阵的元素。这两个条件的变化也会对矩阵元素进行。
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 函数本身不足以满足我的需要。有人能找到解决方案吗?非常感谢
【问题讨论】:
-
你可以看看
ifelsefunction。 -
我认为你需要一些嵌套的
ifelse-statements 或dplyrscase_when函数。
标签: r function if-statement conditional-statements