Search code examples
rdplyr

Specify function inputs in R


I would like to wrap the code below in a function to avoid repeating it multiple times for different input matrices and timepoints. The function should save in the work environment a reshaped data frame, consisting of one row and multiple columns.

library (reshape2)
d28p<-as.matrix(rbind(c(42, 14, 2,  NaN),
                         c(14, 196, 29, 0), 
                         c(0,   22, 36, 3),
                         c(0,   0,  2,  0)))

d28p[d28p=="NaN"]<-0 #replace NaN with 0
d28p<-melt(d28p) #melt
d28p<-t(d28p) #transpose
d28p<-as.data.frame(d28p)[3,] #select the 3rd row
row.names(d28p) <- c("d28") #name the row

I tried this but it didn't work:

p.mtx<-function(nmatrix, timepoint){
  
  nmatrix[nmatrix=="NaN"]<-0 #replace NaN with 0
  nmatrix<-melt(nmatrix) #melt
  nmatrix<-t(nmatrix) #transpose
  nmatrix<<-as.data.frame(nmatrix)[3,] #select the 3rd row
  row.names(nmatrix) <- c("timepoint") #name the row
  
}

p.mtx(nmatrix="d28p", timepoint="Day 28")
p.mtx(nmatrix="m3p", timepoint="Month 3")

Please let me know how to create the function.


Solution

  • Functions in R return the last line you run inside a function, unless you specify which object you wish to return (with return). Thus, you need to specify that the object you wish to return from the function is nmatrix. Also, when you pass nmatrix="d28p" as the first argument of the function, it will pass literally the string "d28p", instead of the matrix named d28p, so you need to remove the quotation marks. The same comment applies for the use of "timepoint" inside the function.

    p.mtx<-function(nmatrix, timepoint){
      
      nmatrix[nmatrix=="NaN"]<-0 #replace NaN with 0
      nmatrix<-melt(nmatrix) #melt
      nmatrix<-t(nmatrix) #transpose
      nmatrix<-as.data.frame(nmatrix)[3,] #select the 3rd row
      row.names(nmatrix) <- timepoint #name the row
      return(nmatrix)
    }
    
    d28<-as.matrix(rbind(c(42, 14, 2,  NaN),
                          c(14, 196, 29, 0), 
                          c(0,   22, 36, 3),
                          c(0,   0,  2,  0)))
    
    resul <- p.mtx(nmatrix = d28, 
                   timepoint = "Day 28")
    
    #       V1 V2 V3 V4 V5  V6 V7 V8 V9 V10 V11 V12 V13 V14 V15 V16
    #Day 28 42 14  0  0 14 196 22  0  2  29  36   2   0   0   3   0