Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to create "fragile" attributes in R?

Is there any way to set an attribute on an object that is removed when it is processed by another function? For example, I might write:

weightedMeanZr <- function(r,n) {
   require(psych)
   Zr <- fisherz(r) 
   ZrBar <- sum(Zr*(n-3))/(sum(n-3))
   attr(ZrBar,"names") <- "ZrBar"
   return(ZrBar)
}

To calculated the weighted fisher transformed Z average for a set of correlations. However, if I convert it back into an r, e.g.

require(psych)
bdata <- structure(list(Sample = 1:6, n = c(4L, 13L, 9L, 5L, 11L, 14L), 
    r = c(0.93, 0.57, 0.46, -0.09, 0.12, 0.32)), .Names = c("Sample", 
"n", "r"), class = "data.frame", row.names = c(NA, -6L))

fisherz2r(with(bdata,weightedMeanZr(r,n)))

The output value from fisherz2r has retained the names attribute from the results of weightedMeanZr. Is there any way to make that attribute fragile such that being processed by functions like fisherz2r removes the names attribute?

Edit Something like what this accomplishes:

weightedMeanZr <- function(r,n) {
   require(psych)
   Zr <- fisherz(r) 
   ZrBar <- sum(Zr*(n-3))/(sum(n-3))
   class(ZrBar) <- "ZrBar"
   return(ZrBar)
}
"+.ZrBar" <- function(e1,e2) {
    return(unclass(e1)+unclass(e2))
}
"-.ZrBar" <- function(e1,e2) {
    return(unclass(e1)-unclass(e2))
}
"*.ZrBar" <- function(e1,e2) {
    return(unclass(e1)*unclass(e2))
}
"/.ZrBar" <- function(e1,e2) {
    return(unclass(e1)/unclass(e2))
}
weightedMeanZr(bdata$r,bdata$n)
weightedMeanZr(bdata$r,bdata$n)+1
weightedMeanZr(bdata$r,bdata$n)-1
weightedMeanZr(bdata$r,bdata$n)*2
weightedMeanZr(bdata$r,bdata$n)/2
fisherz2r(weightedMeanZr(bdata$r,bdata$n))

... but this only works because fisherz2r calls those particular methods... is there a more general approach?

like image 704
russellpierce Avatar asked Dec 02 '25 12:12

russellpierce


1 Answers

You can use unname to remove names

 fisherz2r(with(bdata,unname(weightedMeanZr(r,n))))
 # or
 unname(fisherz2(with(bdata,weightedMeanZr(r,n))))

or as.vector, which in this case will strip the names

like image 158
mnel Avatar answered Dec 04 '25 03:12

mnel