Domanda

I am using the function clhs, which calls on the function cor. I would like to change the default settings that clhs uses for cor.

clhs has the following default settings for cor

cor(data_continuous, use = "complete.obs")

I want to change cor to (data.continuous, use="all.obs") while using clhs.

Does anyone know how to go about this?

È stato utile?

Soluzione

So i'm guessing you were looking specifically at the clhs.data.frame function from the clhs package. Technically, you can change the innards of functions. Here's how to make your requested change. Just to make sure you are modifying the correct line, look at

body(clhs.data.frame)[[10]]

For me at least, that returned the call to cor(). You can change that with

body(clhs.data.frame)[[10]] <- quote(cor_mat <- cor(data.continuous, use="all.obs"))

Then you should be able to use that function as before. But be forewarned that changing how the inside of of a function behaves could cause big problems for other functions that depend on a certain behavior.

A better idea would be to create a copy of the function with a different name that you can explicitly call when you need so it doesn't interfere with anything else.

To show how this works, I'll create a simple example (because the clhs.data.frame function is very big). Let's say theff` function is defined by someone else and we need to use it on our data

ff<-function(x) {
    y <- x+2
    y <- head(y,-1)
    z <- sum(y)
    return( z/2 )
}


ff(c(1,2,3,4,5))     #9
ff(c(1,NA,3,4,5))    #NA

Oh no. Passing an NA in the vector causes a problem. If only they had specified na.rm=T in the sum it would work. So why not change it

body(ff)[[4]]<-quote(z<-sum(y, na.rm=T))
ff(c(1,NA,3,4,5))    #7

Notice that when you call body(ff) you actually see the body of the function. This is actually a list that you can manipulate. Each index corresponds to a command or block of code and body(ff)[[4]] is the line of code that has the sum call. So we just want to swap out that line for our own version (being careful to escape our expression so that it's not evaluated right away). Now when we run the function again, we get the "improved" behavior.

I just wanted to let you know it is possible to change functions like this (which makes R pretty cool) but it also may potentially cause many side effects so you're safer not doing it this way.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top