根据名称有条件地乘以值

Zce*_*mní 6 r dplyr

我有一个数据框,类似:

d <-
  data.frame(
    col1 = c(7, 8, 9),
    col2 = c(12, 7, 0),
    col3 = c(1, 2, 3)
  )
Run Code Online (Sandbox Code Playgroud)

和向量与数字

coefs <-
  c(
    col1  = 4,
    col2  = 6
  )
Run Code Online (Sandbox Code Playgroud)

我需要实现的是如果df中的列名等于向量列,那么我想将其乘以。如果列名不同,丢失或不相等,则应保持不变。

例如,对于上述数据帧和向量,结果应为:

result <-
  data.frame(
    col1 = c(28, 32, 36),
    col2 = c(72, 42, 0),
    col3 - c(1, 2, 3)
  )
Run Code Online (Sandbox Code Playgroud)

我认为最好的方法是使用mutate_if,但是我不确定如何匹配列名。

Ron*_*hah 6

您可以直接在基数R中执行此操作

d[names(coefs)] <- d[names(coefs)] * as.list(coefs)
d

#  col1 col2 col3
#1   28   72    1
#2   32   42    2
#3   36    0    3
Run Code Online (Sandbox Code Playgroud)

  • 了解到一些知识(data.frame和列表乘法)。 (3认同)