How to write a summarySE function in R

I am a new R user and want to make a line chart using stdwith ggplot. To do this, I use the function summarySE.

vrn1_summary<-summarySE(data,measurevar = "vrn1",groupvars = c("genotype","treatment","time"))

Since I cannot perform my own function, I copied the following from the R Cookbook:

summarySE <- function(data=NULL, measurevar, groupvars=NULL, na.rm=FALSE,
                      conf.interval=.95, .drop=TRUE) {
    library(plyr)

    # New version of length which can handle NA's: if na.rm==T, don't count them
    length2 <- function (x, na.rm=FALSE) {
        if (na.rm) sum(!is.na(x))
        else       length(x)
    }

    # This does the summary. For each group data frame, return a vector with
    # N, mean, and sd
    datac <- ddply(data, groupvars, .drop=.drop,
      .fun = function(xx, col) {
        c(N    = length2(xx[[col]], na.rm=na.rm),
          mean = mean   (xx[[col]], na.rm=na.rm),
          sd   = sd     (xx[[col]], na.rm=na.rm)
        )
      },
      measurevar
    )

    # Rename the "mean" column    
    datac <- rename(datac, c("mean" = measurevar))

    datac$se <- datac$sd / sqrt(datac$N)  # Calculate standard error of the mean

    # Confidence interval multiplier for standard error
    # Calculate t-statistic for confidence interval: 
    # e.g., if conf.interval is .95, use .975 (above/below), and use df=N-1
    ciMult <- qt(conf.interval/2 + .5, datac$N-1)
    datac$ci <- datac$se * ciMult

    return(datac)
}

When I call this function, it gives sd(standard deviation), se(standard error) and ci(confidence interval), but shows NAfor meanwhat is "vrn1" in my data, and also shows warnings. As far as I understand, this may be a problem in the function summarySE, but I cannot find out where / why.

Can anyone help me solve this problem. or guide me how to write a simple function summarySE?

+4
1

str(data)

, measurevar vrn1 chr.

0

All Articles