TMOTTM
TMOTTM

Reputation: 3381

Why does my R script only print the last statement

I have this script that reads some data from a directory. I want to print the data and the output from the getwd function to the console. However, only the output from the last statement is printed. Why is that and how can I have all statements print to console?

Here's my function

#!/usr/bin/env Rscript
getmonitor <- function(id, directory, summarize=FALSE)
{
    target <- paste(directory, id, '.csv', sep="")
    target 
    dt <- read.csv(target, header=TRUE)
    dt 
    getwd()
}

getmonitor('001', './specdata/')

What I was hoping for was to first see the output (from dt) and then the working directory.

Upvotes: 0

Views: 781

Answers (1)

Paul Hiemstra
Paul Hiemstra

Reputation: 60944

You will have to wrap them explicitly in print statements. What happens now is that getwd() is returned from the function, and is printed when getmonitor finishes.

getmonitor <- function(id, directory, summarize=FALSE)
{
    target <- paste(directory, id, '.csv', sep="")
    print(target) 
    dt <- read.csv(target, header=TRUE)
    print(dt) 
    print(getwd())
    return(dt)
}

getmonitor('001', './specdata/')

Note that I returned dt as I thought that might be what you need outside the function. If you simply need to have stuff printed inside the function, you can use return(NULL) at the end.

Upvotes: 3

Related Questions