3

R - skip commands based on

 2 years ago
source link: https://www.codesd.com/item/r-skip-commands-based-on.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

R - skip commands based on

advertisements

When I have data matrices

mI <- c(1:4, 2, 6, 9)
mJ <- c(4:1, 5, 0, 2)

and the following simple regression function

fLM <- function(mX, mY){
       lmXY <- lm(mY~mX)
       summary(lmXY)
       return(lmXY)
}

It is obvious that I want to print the outcomes of the regression in the function by using the command summary(lmXY). But using LM <- fLM(mI, mJ) the summary output is not printed, even though this command is included in the function. Strangely (for me at least) summary(lmXY) is printed when I remove the return(lmXY) command in function fLM. Can someone explain why this happens?

Something similar occurs when I establish a Bloomberg connection in a function using

conn <- blpConnect()

A couple of commands later in the function I use blpDisconnect(conn) to disconnect from Bloomberg. The next command returns the retreived data. But while blpConnect() works perfectly, the blpDisconnect(conn) command is skipped. The return of the data is executed perfectly. When I manually establish a connection with Bloomberg and then use the disconnect function there is no problem. But somehow in functions which include return (I am not sure whether this is the cause though, it is merely an observation) there is a problem. Does anybody knows why?

Global code of BB function:

fnBB <- function(){
        conn <- blpConnect()
        ...
        blpDisconnect(conn)
        return(mData)
}

Many thanks in advance.


Objects don't get printed in a function unless:

  1. You explicitly tell the function to print it.
  2. That object is what is returned by the function.

You should run print(summary(lmXY)) instead.

f1 <- function() {1 ; 2}
f2 <- function() {print(1) ; 2}
f3 <- function() {print(1) ; return(2)} # identical to f2

f1() #prints 2
object = f1() #stores 2, prints nothing
object = f2() #stores 2, prints 1
f2() #prints 1 and 2


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK