如何迭代两列之间的乘法来创建新列?

问题描述 投票:0回答:1

我有 6 个评级,我必须将它们乘以各自的权重(这是 nasa tlx)才能获得每个域的加权评级,如下所示:

6 条评价 r_精神、r_物理、r_时间、r_努力、r_表现、r_挫败

6 个重量: w_精神、w_物理、w_时间、w_努力、w_表现、w_挫折

我必须将每个 r_xxx 与每个 w_xxx 相乘以获得“weighted_xxx”列。

现在,为了制作新专栏,我只需这样做:

mutate(nasa, weighted_mental = r_mental*w_mental) 

我可能已经手动编写这一行六次以获得weighted_physical、weighted_temporal等,但我确信有一种更聪明的方法来做到这一点。

如何对连续列迭代操作 6 次?如何让 r 正确获取weighted_xxx 列的名称?

r dataframe dplyr iteration mutate
1个回答
0
投票

您尝试做的问题是您的数据实际上并不整洁。您应该阅读该内容,但 tl;dr 版本是您不应该在列名称中对重要信息进行编码。将这些数据分解到它自己的列中。一旦完成,操作就变得异常简单:

# load libraries and setting the random seed
library(tidyverse)
set.seed(0)

# creating the sample dataset
nms <- c("r_mental", "r_physical", "r_temporal", "r_effort", "r_performance", "r_frustration",
         "w_mental", "w_physical", "w_temporal", "w_effort", "w_performance", "w_frustration")

df <- data.frame(matrix(sample(1:100, 12*10, replace=T), ncol=12, dimnames=list(NULL, nms)))


df |>
  # tidy the data
  pivot_longer(cols = everything(), names_to = c(".value", "type"), names_pattern = "(\\w)_(\\w+)") |>
  # add the weighted column
  mutate(weighted = r * w)

输出:

# A tibble: 60 × 4
   type            r     w weighted
   <chr>       <int> <int>    <int>
 1 mental         14    75     1050
 2 physical       51    29     1479
 3 temporal       37    17      629
 4 effort         70    51     3570
 5 performance    40    29     1160
 6 frustration    14    40      560
 7 mental         68    81     5508
 8 physical       97    13     1261
 9 temporal       89    73     6497
10 effort         74    93     6882
# ℹ 50 more rows
© www.soinside.com 2019 - 2024. All rights reserved.