library(Rcpp)
library(geoR)
elevationd=as.matrix(data.frame(xcoords=elevation$coords[,1],
ycoords=elevation$coords[,2], elev=elevation$data))
elevationd
cppFunction('void a(NumericMatrix data){
int nr = data.nrow();
int nc = data.ncol();
NumericVector tmp;
for (int i; i<nr; i++){
tmp[i] = data(i,2);
}
NumericMatrix mat(nr, nr);
for (int i; i<nr; i++){
for (int j; j<nr; j++){
mat(i,j) = (tmp[i] - tmp[j])*(tmp[i] - tmp[j]);
}
}
}')
a(elevationd)
i have a r code like this.
But when i implement this, i got "R Session Aborted. R encountered a fatal error. The session was terminated." message.
but i Can't find any problem with my code.
I wonder if it is the problem of the hardware........ not my code T.T
ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ
thx to Dirk
This is my edited code.
cppFunction('NumericMatrix f1(NumericMatrix data){
int nr = data.nrow();
int nc = data.ncol();
NumericMatrix mat(nr, nr);
for (int i=0; i<nr; i++){
for(int j=0; j<nr; j++){
mat(i,j) = (data(i,2)-data(j,2))*(data(i,2)-data(j,2));
}
}
return mat;
}')
Roland already gave you a good hint, you also had two types wrong and missed a size on the vector initialization.
Below is a repaired version, as a C++ file you can source with the relevant R code being executed automatically:
R> Rcpp::sourceCpp("/tmp/jiwon.cpp")
R> library(geoR)
--------------------------------------------------------------
Analysis of Geostatistical Data
For an Introduction to geoR go to http://www.leg.ufpr.br/geoR
geoR version 1.7-5.2 (built on 2016-05-02) is now loaded
--------------------------------------------------------------
R> elevationd <- as.matrix(data.frame(xcoords=elevation$coords[,1],
+ ycoords=elevation$coords[,2],
+ .... [TRUNCATED]
R> str(elevationd)
num [1:52, 1:3] 0.3 1.4 2.4 3.6 5.7 1.6 2.9 3.4 3.4 4.8 ...
- attr(*, "dimnames")=List of 2
..$ : chr [1:52] "1" "2" "3" "4" ...
..$ : chr [1:3] "xcoords" "ycoords" "elev"
R> str(a(elevationd))
num [1:52, 1:52] 0 5929 13225 32400 4900 ...
R>
And here is the repaired code addressed a few of your errors:
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
NumericMatrix a(NumericMatrix data){
int nr = data.nrow();
int nc = data.ncol();
NumericVector tmp(nr);
for (int i=0; i<nr; i++){
tmp[i] = data(i,2);
}
NumericMatrix mat(nr, nr);
for (int i=0; i<nr; i++){
for (int j=0; j<nr; j++){
mat(i,j) = (tmp[i] - tmp[j])*(tmp[i] - tmp[j]);
}
}
return mat;
}
/*** R
library(geoR)
elevationd <- as.matrix(data.frame(xcoords=elevation$coords[,1],
ycoords=elevation$coords[,2],
elev=elevation$data))
str(elevationd)
str(a(elevationd))
*/