Hotel <- function(hotel) { require(data.table) dat <- read.csv("demo.csv", header = TRUE) dat$Date <- as.Date(paste0(format(strptime(as.character(dat$Date), "%m/%d/%y"), "%Y/%m"),"/1")) library(data.table) table <- setDT(dat)[, list(Revenue = sum(Revenues), Hours = sum(Hours), Index = mean(Index)), by = list(Hotel, Date)] answer <- na.omit(table[table$Hotel == hotel, ]) if (nrow(answer) == 0) { stop("invalid hotel") } return(answer) } #Reads the dataframe from the Hotel Function star <- (Hotel("Hotel Name")) #Calculates the Revpar and Index Revpar <- star$Revenue / star$Rooms Index <- star$Index png(filename = "~/Desktop/result.png", width = 480, height= 480) plot(Index, Revpar, main = "Hotel Name", col = "green", pch = 20) testing <- cor.test(Index, Revpolu) write.table(testing[["p.value"]], file = "output.csv", sep = ";", row.names = FALSE, col.names = FALSE) dev.off()