made a mistake in the part that says:
sink(file = file.path(getwd(),"Reports/model_log.txt"),
append = TRUE, type = "output")
this should say:
sink(file = outfile,
append = TRUE, type = "output")
문제
I am trying to write a function that performs several stepwise regressions and outputs the 'steps' of each one to a text file. The problem I am having is that sink() doesn't actually output anything since none of the operations in the function show up in the R console.
Edit: The problem actually seems to arise in the first part of my function. The file "model_log.txt" never even gets created, so something tells me sink won't work at all within a function.
This is my function so far:
stepModel <- function(formula, family = binomial, data, outfile = NULL) {
if (is.null(outfile) == FALSE){
sink(file = file.path(getwd(),"Reports/model_log.txt"),
append = TRUE, type = "output")
print("")
print("Models run at: ")
print(Sys.time())
}
model.initial <- glm(formula, family = family, data = data)
summary(model.initial)
model.stepwise1 <- step(model.initial, direction = "backward")
summary(model.stepwise1)
model.stepwise2 <- step(model.stepwise1, scope = ~.^2)
summary(model.stepwise2)
if (is.null(outfile) == FALSE) sink()
output <- list(modInitial = model.initial, modStep1 = model.stepwise1, modStep2 = model.stepwise2)
return(output)
}
I am using the following dataframe to test my results (never mind that the stepwise regression removes everything but the intercept, this is enough for you to repeat my results):
test.df <- data.frame(a = sample(0:1, 100, rep = T),
b = as.factor(sample(0:5, 100, rep = T)),
c = runif(100, 0, 100),
d = rnorm(100, 50, 50))
test.mdl <- stepModel(a~., family = binomial, data = test.df, outfile = file.path(getwd(), "test_log.txt"))
I want this function to send all these steps to whatever file is specified in the outfile option. Any ideas?
해결책
made a mistake in the part that says:
sink(file = file.path(getwd(),"Reports/model_log.txt"),
append = TRUE, type = "output")
this should say:
sink(file = outfile,
append = TRUE, type = "output")