本文介绍了循环以跨列相乘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据帧,其中的列标记为sales1sales2price1price2,我想通过将sales1 * price1等乘以迭代的时尚.

I have a data frame with columns labeled sales1, sales2, price1, price2 and I want to calculate revenues by multiplying sales1 * price1 and so-on across each number in an iterative fashion.

data <- data_frame(
  "sales1" = c(1, 2, 3),
  "sales2" = c(2, 3, 4),
  "price1" = c(3, 2, 2),
  "price2" = c(3, 3, 5))

data
# A tibble: 3 x 4
#  sales1 sales2 price1 price2
#   <dbl>  <dbl>  <dbl>  <dbl>
#1      1      2      3      3
#2      2      3      2      3
#3      3      4      2      5

以下代码为什么不起作用?

Why doesn't the following code work?

data %>%
  mutate (
    for (i in seq_along(1:2)) {
      paste0("revenue",i) = paste0("sales",i) * paste0("price",i)
    }
  )

推荐答案

假定您的列已经排序(sales1sales2price1price2).我们可以将数据帧分为两部分,然后相乘

Assuming your columns are already ordered (sales1, sales2, price1, price2). We can split the dataframe in two parts and then multiply them

data[grep("sales", names(data))] * data[grep("price", names(data))]

#  sales1 sales2
#1      3      6
#2      4      9
#3      6     20

如果尚未按名称对列进行排序,则可以使用order然后使用上面的命令对它们进行排序.

If the columns are not already sorted according to their names, we can sort them by using order and then use above command.

data <- data[order(names(data))]

这篇关于循环以跨列相乘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 07:04