[R] how to coerce the result of sweep to be an array if result of FUN is a string?
Rui Barradas
ruipbarradas at sapo.pt
Sat Aug 4 23:50:10 CEST 2012
Hello,
You can coerce the result to the input shape by assigning the dim
attribute by hand.
string.ans <- sweep(m, c(2,3), stat, string.fun)
dim(string.ans) <- dim(m)
string.ans
Or put this in a function.
# An abbreviation and the complete function name
sweep.ch <- sweep.character <-
function(x, MARGIN, STATS, FUN="-", check.margin=TRUE, ...){
result <- sweep(x, MARGIN, STATS, FUN, check.margin, ...)
dim(result) <- dim(x)
result
}
string.ans2 <- sweep.ch(m, c(2,3), stat, string.fun)
string.ans2
Hope this helps,
Rui Barradas
Em 04-08-2012 20:35, Peter Young escreveu:
> Hi,
>
>
>
> I would like to use sweep to "sweep out" proportions and confidence intervals for an array, however when I supply a function which returns a string (containing something like "9% (3-18%)") I get back a list instead of an array, here is a simplified example:
>
>
>
> # example showing that sweep does not return an array with same dimensions as STATS as advertised
>
>
>
> string.fun <- function(a, b) {
>
> paste(a, "-", b, sep="")
>
> }
>
> num.fun <- function(a, b) {
>
> a+b/100
>
> }
>
> m <- array(seq(1:24), dim = c(2,3,4))
>
> stat <- array(seq(1:12), dim = c(3,4))
>
>
>
> string.ans <- sweep(m, c(2,3), stat, string.fun)
>
> dim(string.ans)
>
> length(string.ans)
>
> num.ans <- sweep(m, c(2,3), stat, num.fun)
>
> dim(num.ans)
>
>
>
> Although the contents are correct, strings.ans is a list while num.ans is an array. Help(sweep) says that the result of sweep should have the same dimensions as x, however when the result of the function is a string this is not the case. How can I coerce the result of the function to cause sweep to return an array as advertised?
>
>
>
> thanks,
>
> Peter
>
>
>
> Peter Young, MPH
>
> Surveillance Epidemiologist
>
> CDC Mozambique
>
>
>
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
More information about the R-help
mailing list