[R] Make sure a data frame has been "fun through" a function
Charles C. Berry
ccberry at ucsd.edu
Tue Feb 21 17:30:45 CET 2017
On Tue, 21 Feb 2017, stephen sefick wrote:
> Sorry for not being clear. I have never used S3 methods before. Below is
> some R code that sketches out my idea. Is this a sensible solution?
>
Sure. See comments (untested) inline.
Chuck
> test_data <- data.frame(a=1:10, b=1:10, c=1:10)
>
> functionA <- function(x, impossible_genotype){
> ##some data processing
> y <- x
>
> ##return S3 to be able to use impossible genotype later
> class(y) <- append(class(y),"genotypes")
class(y) <- c("genotypes",class(y))
>
> attr(y, "impossible_genotype") <- impossible_genotype
>
> return(y)
> }
>
> test_data_genotypes <- functionA(test_data, impossible_genotype="Ref")
>
> functionB <- function(x){
> ##stop if pre-processed with functionA
> if(sum(class(x)=="genotypes")!=1){stop("Need to pre-process data with
> functionA")}
if(!(inherits("genotypes")){
stop("Need to pre-process data with functionA")}
or in functionA you could skip the class()<- and just set the
"impossible_genotypes" attribute to FALSE when there are none such.
Then here test
if (is.null(attr(x,"impossible_genotypes"))){
stop("Need to pre-process data with functionA")
} else {
return(alleles)
}
>
> ##use this later in functionB to
> impossible_genotype <- attributes(x)$impossible_genotype
impossible_genotype <- attr(x,"impossible_genotype")
>
> alleles <- c("Ref", "Alt")
>
> coded_genotype <- alleles[alleles!=impossible_genotype]
maybe `!is.element(alleles,impossible_genotype)' is safer than `!='
>
>
>
> return(coded_genotype)
> }
>
> ##stop if not pre-processed with functionA
> functionB(test_data)
>
> ##processed with functionA
> functionB(test_data_genotypes)
>
More information about the R-help
mailing list