60 likes | 111 Views
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 )}
E N D
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).
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)}
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.
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
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