i have 2 data frames. in last column ("bill") in first data frame, want apply function (fixed price + quantity*price/qty). in order apply function, r should match values in first column of df1 column names of df2.
i have solved problem creating function , several ifelse statements, want use statement automatically matches values in df1 column names in df2. data set have contains more 2 million rows , need apply same rationale building other similar functions. nice use not require loop or takes long process.
### set data frames ### code <- c("a1", "a2", "c3", "a1") name <- c("dan", "david", "anna", "lisa") quantity <- c(30, 12, 10, 10) df1 <- as.data.frame(cbind("code" = code, "name" = name, "quantity" = quantity), stringsasfactors = f) df1$quantity <- as.numeric(df1$quantity) fixed_price <- c(12, 5, 23) price_per_qty <- c(1, 4, 7) df2 <- as.data.frame(rbind("fixed_price" = fixed_price, "price_per_qty" = price_per_qty)) colnames(df2) <- c("a1", "a2", "c3") ### combine dataframe 1 , 2 single dataframe ### # code below pulls individual columns df2 based on # index provided "code" column in df1, transposes them # they'll line df1, column binds them df1 df3 <- cbind(df1, t(df2[,df1$code])) # bill calculated enough bill <- df3[4] + df3[3] * df3[5] colnames(bill) <- "bill" # finally, output results wanted cbind(df3, bill)
Comments
Post a Comment