I have the following data frame:
y <- data.frame(group = letters[1:5], a = rnorm(5) , b = rnorm(5), c = rnorm(5), d = rnorm(5) )
How to
You can use apply to apply a function to each row (or column) of a matrix, array or data.frame.
apply(
y[,-1], # Remove the first column, to ensure that u remains numeric
1, # Apply the function on each row
function(u) cor( u[1:2], u[3:4] )
)
(With just 2 observations, the correlation can only be +1 or -1.)