Search code examples
rif-statementcountformula

How to write formulas for counting different values in data frame


The assignment is as follows.

Q2. Write a function with one argument, say, data. The function does following,

  1. If the argument data is a character vector, count the total number of characters;
  2. If the argument data is numeric vector, calculate the mean, sd, min, and max values;
  3. The function should return the value using list, containing also data.

I am very new to this and would like to use basic R code to solve it. I don't really understand the syntax I ought to use.


Solution

  • You may want to upload some data examples. I am assuming your 'data' is pure character or numbers. See code below. But detailed information will be needed if it does not work for you.

    myfunc=function(data){
      if(is.character(data)){
        res=list(data=data, Nchar=sum(nchar(data)))
      }
      else if(is.numeric(data)){
        res=list(data=data, mean=mean(data), sd=sd(data),max=max(data), min=min(data))
      }
      return(res)
    }
    #usage
    data1=c("a","bbb")
    myfunc(data1)
    data2=c(1,2,3)
    myfunc(data2)