I have a data frame with the following columns:
sales_1, sales_2, price_1, price_2

Now, I want to calculate revenues by multiplying sales_1 * price_1 and so-on across each number in an iterative manner.

Below is my sample data

```sample_data <- data_frame(
"sales_1" = c(10, 20, 30),
"sales_2" = c(20, 30, 40),
"price_1" = c(30, 20, 20),
"price_2" = c(30, 30, 50))

sample_data
# A tibble: 3 x 4
#  sales_1 sales_2 price_1 price_2
#   <dbl>  <dbl>  <dbl>  <dbl>
#1    10      20      30      30
#2    20      30      20      30
#3    30      40      20      50```

I have tried the following code. But this does not work.

```sample_data %>%
mutate (
for (i in seq_along(1:2)) {
paste0("total_revenue",i) = paste0("sales_",i) * paste0("price_",i)
}
)``` Apr 6, 2018 5,489 views

## 1 answer to this question.

I am assuming that your columns are already ordered as (sales_1, sales_2, price_1, price_2)

So now, I would suggest you to split the data frame into 2 parts and then multiply them.

```sample_data[grep("sales_", names(sample_data))] * sample_data[grep("price_", names(sample_data))]

#  sales_1 sales_2
#1      300      600
#2      400      900
#3      600     2000```

Just in case if you're columns are not sorted according to their names. You can sort them by using order() as follows:

`sample_data <- sample_data[order(names(sample_data))]` answered Apr 6, 2018 by
• 2,090 points

## How to extract specific columns from a dataframe in R?

Hi@akhtar, You can use the select method to ...READ MORE

## How to replace NA values in a dataframe with Zero's ?

It is simple and easy: df1<-as.data.frame(matrix(sample(c(NA, 1:10), 100, ...READ MORE

## How to extract specific columns from a DataFrame ?

Yes there are so many ways: df[,c(V2,V4)] and another ...READ MORE

+1 vote

## How to convert a list of dataframes in to a single dataframe using R?

You can use the plyr function: data <- ...READ MORE

+1 vote

## How to sort a data frame by columns in R?

You can use dplyr function arrange() like ...READ MORE

## How to apply list to a function which give data frame as output

If you use  tidyverse, you can use ...READ MORE

## How to remove NA values with dplyr::filter()

Try this: df %>% filter(!is.na(col1)) READ MORE