1 / 6

Functions with R

Functions with R. Functions follow this grammar (in italics what you should change): nameOfTheFunction <- function( argument1 , argument 2 ,…) { TS <- body of the function return( TS )}

Download Presentation

Functions with R

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Functions with R • Functions follow this grammar (in italics what you should change): • nameOfTheFunction <- function(argument1, argument 2,…){TS<-body of the functionreturn(TS)} • The return() function indicates what your own function should give after being evaluated (eg. if the function is mean then the value being returned should be the mean).

  2. Example of a function: my.mean() • The following function computes the mean • my.mean <- function(data){meanDC<-sum(data,na.rm=T)/length(!is.na(data))return(meanDC)}

  3. During lab: write a function for SD

  4. Applying the function to all rows • apply(data,margin,function,argument of previous function) is a function that will apply (!) whatever function you provide to either each row or each column of your dataframe • Use the apply function to compute SD by subject on mood on Tuesday and mood on Sunday.

  5. Assignment: write a function for MSSD • Begin by coding the MSSD specifically for the 6 measures of mood of the mood data • Think about how to generalize your codeHints: • You could do a loop: for the first value, take the difference between value 1 and 2, square it, then for the second value, take the difference … • You could subtract the vector of values to the vector of the same value at time t+1, then square the elements of the resulting difference vector

  6. Assignment: apply your function • Apply the SD and the MSSD functions to the data on mood • Obtain the mean SD and MSSD across subjects per day

More Related