library(tidyverse)
library(dplyr)
# Input test data
Component2 <- data.frame(
stringsAsFactors = FALSE,
Component_Product_Code = c("Component6",
"Component7","Component8","Component9","Component22"),
Quantity = c(1L, 2L, 4L, 28L, 90L),
Wastage_Quantity = c(0L, 0L, 0L, 0L, 0L),
Unit_Cost = c(127.2, 112.02, 23.33, 0.0342, 0.0453),
Total_Cost = c(127.2, 224.04, 93.32, 0.9576, 4.077),
Can_Auto_Assemble = c("Yes", "Yes", "Yes", "Yes", "Yes"),
Can_Auto_Disassemble = c("No", "No", "No", "No", "No"),
IsObsoleted = c("No", "No", "No", "No", "No"),
Expense_Account = c(NA, NA, NA, 51120L, 51120L),
Comments = c(NA, NA, NA, NA, NA)
)
Component9 <- data.frame(
stringsAsFactors = FALSE,
Component_Product_Code = c("Component11",
"Component12","Component13","Component14",
"Component15"),
Quantity = c(5L, 5L, 2L, 1L, 1L),
Wastage_Quantity = c(0L, 0L, 0L, 0L, 0L),
Unit_Cost = c(107, 53, 49.3629, 55.3854, 134.186),
Total_Cost = c(535, 265, 98.7258, 55.3854, 134.186),
Can_Auto_Assemble = c("Yes", "Yes", "Yes", "Yes", "Yes"),
Can_Auto_Disassemble = c("No", "No", "No", "No", "No"),
IsObsoleted = c("No", "No", "No", "No", "No"),
Expense_Account = c(51250L, 51244L, NA, NA, NA),
Comments = c(NA, NA, NA, NA, NA)
)
Component14 <- data.frame(
stringsAsFactors = FALSE,
Component_Product_Code = c("Component16",
"Component17","Component18","Component19",
"Component20","Component21"),
Quantity = c(68L, 4L, 2L, 34L, 2L, 34L),
Wastage_Quantity = c(0L, 0L, 0L, 0L, 0L, 0L),
Unit_Cost = c(0.036, 0.2768, 0.0255, 0.0645, 0.6502, 0.16),
Total_Cost = c(2.448, 1.1072, 0.051, 2.193, 1.3004, 5.44),
Can_Auto_Assemble = c("No", "No", "No", "No", "No", "No"),
Can_Auto_Disassemble = c("No", "No", "No", "No", "No", "No"),
IsObsoleted = c("No", "No", "No", "No", "No", "No"),
Expense_Account = c(51120L, NA, 51120L, 51120L, NA, 51120L),
Comments = c(NA, NA, NA, NA, NA, NA)
)
Updated_price_list <- data.frame(
stringsAsFactors = FALSE,
Assembled_Product_Code = c("Component1", "Component3", "Component10"),
Total_Cost = c(13.5682, 12.5396, 300.4532)
)
# I have three data.frames. For each one, I need to get the sum of column Total_Cost and add to an existing csv.
# As an example, the .csv file is provided here as a data.frame.
# Many thanks in advance for your assistance.
# Placing the data frames into a list.
List <- list(Component14, Component2, Component9)
# Making a function to sum the Total_Cost column.
TotalCost <- function(x){
sum(Total_Cost)
}
# Using lapply to make a list of sums for each data frame.
# However, I get the error message "Error in FUN(X[[i]], ...) : object 'Total_Cost' not found"
Cost_sum <- (lapply(List, TotalCost))
# Adding the sums to the existing .csv file
write.table(Cost_sum, file = "Updated_price_list.csv", sep = ",",
append = TRUE, quote = FALSE,
col.names = FALSE, row.names = FALSE)