[R] apply diff type function to matrix
David L Carlson
dcarlson at tamu.edu
Thu Jun 19 16:48:29 CEST 2014
I'm not sure we have enough information, but given your matrix:
> mt <- matrix(c(1, 2, 3, 10, 15, 20, 20, 40, 80, 30, 60, 120), 3, 4)
> mt
[,1] [,2] [,3] [,4]
[1,] 1 10 20 30
[2,] 2 15 40 60
[3,] 3 20 80 120
# Get differences between adjacent values in each column
> mt.d <- abs(diff(mt))
> mt.d
[,1] [,2] [,3] [,4]
[1,] 1 5 20 30
[2,] 1 5 40 60
# Get ratio of cols 2-4 to col 1
> mt.d[,-1]/mt.d[,1]
[,1] [,2] [,3]
[1,] 5 20 30
[2,] 5 40 60
# Get ratio of cols 2-4 to cols 1-3
> mt.d[,-1]/mt.d[,1:3]
[,1] [,2] [,3]
[1,] 5 4 1.5
[2,] 5 8 1.5
-------------------------------------
David L Carlson
Department of Anthropology
Texas A&M University
College Station, TX 77840-4352
-----Original Message-----
From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf Of message
Sent: Thursday, June 19, 2014 8:42 AM
To: r-help at r-project.org
Subject: [R] apply diff type function to matrix
Readers,
For a matrix:
1 10 20 30
2 15 40 60
3 20 80 120
Using a spreadsheet, a differential function can be applied to the data
as a formula:
|(10-15)/(1-2)| ... repeated for each pair of adjacent values
What is the corresponding function in R please?
Is it better to write a new function, or to use some form of function
'diff'?
______________________________________________
R-help at r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
More information about the R-help
mailing list