-1

I have a data frame (df) with two variables shown below:

   pricePerBusiness num_businesses
1           4228.966         3755
2           4966.552         3243
3           4678.073         3109
4           4752.259         2990
5           4545.194         2949 

I want to make a new data frame which is a product of this dataframe and a scalar (15 in this example) that increases in value (1,2,3,...) for each row, example:

df2[1,] <- 1*df[1,]$pricePerBusiness + 0.15*df[1,]$num_businesses - 15*1
df2[2,] <- 1*df[2,]$pricePerBusiness + 0.15*df[2,]$num_businesses - 15*2
df2[3,] <- 1*df[3,]$pricePerBusiness + 0.15*df[3,]$num_businesses - 15*3

And so on. My dataframe (df) however has many rows, is there a quicker way to do this?

PMc
  • 95
  • 10

4 Answers4

0

modify your scalar with

as.numeric(rownames(df))*0.15
Peter Hahn
  • 148
  • 8
0

Below is a possible dplyr solution. Please make sure that your questions are reproducible.

# importing dplyr
library(dplyr)

# reproducing your original data frame
df <- data_frame(
  pricePerBusiness = c(4228.966, 4966.552, 4678.073, 4752.259, 4545.194),
  num_businesses = c(3755, 3243, 3109, 2990, 2949)
)

# creating the final data frame you want
df2 <- df %>%
  mutate(
    # constructing the term to substract
    penalty = 15 * 1:nrow(df),
    # computing the value needed
    value = pricePerBusiness + (0.15 * num_businesses) - penalty
  )
OzanStats
  • 2,756
  • 1
  • 13
  • 26
  • Thanks for that - I see what you mean by reproducible now and will take that on board in the future. – PMc Jul 08 '18 at 18:36
  • This solution is more efficient than computing each column separately. You may want to benefit from the power of `dplyr` or `data.table` in this kind of data handling problems. – OzanStats Jul 08 '18 at 18:42
0

Also, using with() in base:

with(df,
  df2 <<- data.frame(result = pricePerBusiness + 0.15 * num_businesses - 15 *
                              (1:length(num_businesses)))
)
IanRiley
  • 233
  • 1
  • 10
0

I do not have a lot of know about df but i search and find this links i hope it will help you

mai
  • 5
  • 2