I need to write a function to divide a column by an element of a matrix if two conditions are met. These two conditions change also does the matrix element.
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')))
I need to write something like this:
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])
I know the ifelse
function itself isn't enough to get what I need. Would someone be able to find a solution? Thanks a lot
CodePudding user response:
Using within
and same subsets on LHS and RHS.
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