【问题标题】:Arithmetic operation using a conditional statement使用条件语句的算术运算
【发布时间】: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 或dplyrs case_when 函数。

标签: r function if-statement conditional-statements


【解决方案1】:

在 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-19
    • 2012-03-26
    • 2013-10-14
    • 1970-01-01
    • 2013-07-28
    • 2017-09-20
    相关资源
    最近更新 更多