How to create a statistical data function in rstudio?

0

I have the following code:

rm(list=ls(all=T))#limpia todo lo antes escrito

library(tuneR) #libreria para manipular archivos de audio

library(e1071)#libreria para sacar la skewness y kurtosis

directorio<-"/home/roy/Descargas/audios"   #variable donde se almacena el directorio

ld <- list.dirs(directorio, recursive = FALSE)# Se abre el directorio principal


#se inicialisa la variable deacuerto a lo que el usario desee fracmentar el audio
tiempo_de_inicio<-50000
duracion<-tiempo_de_inicio 
cons<-duracion

w<-1
k<-1
fi<-""
inicio<-0

Nombre<-""
Media<-""
Mediana<-""
Moda<-""
Skewness<-""
Kurtosis<-""
z<-""
xy<-""
pk<-""

####################################### FUNCION MODA #########################################

Mode <- function(x) {
ux <- unique(x)
ux[which.max(tabulate(match(x, ux)))]
}

################################ FUNCION PDF #########################################
graficas_pdf= function (parte,i,j,w){ #funcion que sirve para generar los   graficos en pdf

nombre<-paste(i,'/',j,"_",w,".pdf",sep = "")
pdf(file =nombre)
plot(parte)  
dev.off()  

}
   ###########################################################################


for (i in ld) {            # Se recoren las subcarpetas

  lf <- list.files(i)        # se en lista lo que alla en ellas 

    for (j in lf) {               #se recorren los archivos 

     dire<-i
     setwd(dire)                #se fija el nuevo directorio
     cat('Directorio', i, 'archivo', j, '\n') 

     pista<-readWave(j)                 #se lee el archivo .wave
     canalizq<- mono(pista, "left")      #se extrae el canal izquierdo


     [email protected]            #se saca la frecuencia en la que esta el audio

       if(frecuencia==44100){                # busca en que frecuencia se encuentra el audio #frecuencia de 44100 repeticiones por segundo 

         duracion<-tiempo_de_inicio*4        #incrementa las variables dependiendo de la frecuencia
         cons<-duracion

         submuestreo<- downsample(canalizq,frecuencia)   #se extrae el canadel dependiendo de la frecuencia


          for(y in 1:length(submuestreo)){              #se recorre el canal extraido

            if(duracion<=length(submuestreo)) { 
            #Se extraen los fracmentos de acuerdo al tamaño que el usuario dio

             parte<- extractWave(submuestreo,from = inicio, to =duracion,xunit =c("samples", "time"))  #se extrae el espectro

             graficas_pdf(parte,i,j,w)                  #se aplica la funcion para guardar en pdf


               x=parte@left                        #se extrae la parte izquierda del espectro para sacar los datos estadisticos


               Media[k]<-mean(x)

               Mediana[k]<- median(x)

               Moda[k]<-Mode(x)

               Skewness[k]<-skewness(x)

               Kurtosis[k]<-kurtosis(x) ##latex

               Nombre[k]<-paste(j,"_",w,".pdf",sep = "")


               df<- data.frame( Nombre,Media, Mediana, Moda, Skewness,Kurtosis )

               inicio=inicio+cons                         
               duracion=duracion+cons

               w=w+1

        }else if(duracion>length(submuestreo)){            

        print("El audio es menos al fracmento que se pide")
        break;
      }
      k=k+1

    }


    inicio=0          
    duracion<-tiempo_de_inicio
    w=1


  }


  direc<-paste(directorio,"/Datos_Estadisticos.csv",sep = "") #se le pasa el directorio y se aumente el nombre del archivo

  write.csv(df,file=direc) #se crea el archivo que contendra los datos estadisticos


 }

what the code generates is:

All the code works perfectly, the function of this program is to take some audios that are in the path Downloads / audios then process them and extract the left channel with which their spectra are generated by means of pdf and remove the statistical data, saving them in a .csv file. the question is that in the part of the code where the statistical data are taken ---- >

        Media[k]<-mean(x)

        Mediana[k]<- median(x)

        Moda[k]<-Mode(x)

        Skewness[k]<-skewness(x)

        Kurtosis[k]<-kurtosis(x) ##latex

        Nombre[k]<-paste(j,"_",w,".pdf",sep = "")


        df     <- data.frame( Nombre,Media, Mediana, Moda, Skewness,Kurtosis )

how to make that code can convert it to a function and then just call the function.

    
asked by Roge 08.01.2018 в 03:57
source

1 answer

0

To encapsulate a piece of code in a function, first of all you have to define what the input will be and what the expected output will be. Looking at your code a bit, I see that the input should be:

  • x : the data, surely a vector, we will call it data .
  • j : I understand that it is the name of a file, we will call it fname
  • w : it seems to be an accountant, we will call it nfile

The output, so you see the code should be a row of data.frame that we will have to add it to a data.frame general.

Let's see how we would define the routine:

get_data <- function(data, fname, nfile) {
    return(data.frame(Media = mean(data),
                      Mediana = median(data),         
                      Moda = Mode(data),         
                      Skewness = skewness(data),         
                      Kurtosis = kurtosis(data),         
                      Nombre = paste(fname,"_",nfile,".pdf",sep = "")
    ))
}

To use it:

# Antes que nada, afuera de todos los ciclos 
# tenemos que inicializar la variable df como un data.frame vacio
df <- data.frame() 

# Ahora sí dentro del ciclo, agregamos cada "fila" de datos obtenidas
# al data.frame general
df <- rbind(df, get_data(x, j, w))

Some comments:

  • In general I have the criterion that the functions do not have access to global variables, but the truth is that we could also pass df per parameter and that the same function is the one that invokes rbind() and is adding the rows.
  • If the function is going to share it is always good to incorporate a requiere(library) to indicate the additional packages that it requires to work and be able to load them, I say it for the non-standard functions skewness and kurtosis .
  • As you can see, we eliminate the need for intermediate matrices: Nombre , Media , Mediana , Moda , Skewness and Kurtosis , which simplifies the code a lot.
answered by 08.01.2018 / 14:55
source