Brian Caffo. Using.Call in R



Similar documents
An Incomplete C++ Primer. University of Wyoming MA 5310

Compiling Object Oriented Languages. What is an Object-Oriented Programming Language? Implementation: Dynamic Binding

Python, C++ and SWIG

Importing Data into R

Beginning to Program Python

Moving from CS 61A Scheme to CS 61B Java

by the matrix A results in a vector which is a reflection of the given

How To Create A Tree In R

C++ Wrapper Library for Firebird Embedded SQL

Lecture 5: Java Fundamentals III

5 Arrays and Pointers

Lecture 2 Mathcad Basics

MATH 304 Linear Algebra Lecture 9: Subspaces of vector spaces (continued). Span. Spanning set.

Solving Quadratic Equations by Factoring

Deal with big data in R using bigmemory package

The C Programming Language course syllabus associate level

CS1112 Spring 2014 Project 4. Objectives. 3 Pixelation for Identity Protection. due Thursday, 3/27, at 11pm

Problems and Measures Regarding Waste 1 Management and 3R Era of public health improvement Situation subsequent to the Meiji Restoration

Reading and writing files

Using C to Access Data Stored in Program Space Memory on the TMS320C24x DSP

Solution to Homework 2

csce4313 Programming Languages Scanner (pass/fail)

Section 5.3. Section 5.3. u m ] l jj. = l jj u j + + l mj u m. v j = [ u 1 u j. l mj

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

14:440:127 Introduction to Computers for Engineers. Notes for Lecture 06

Specifications of Paradox for Windows

Java CPD (I) Frans Coenen Department of Computer Science

Chapter 7: Additional Topics

MarshallSoft AES. (Advanced Encryption Standard) Reference Manual

Reductions & NP-completeness as part of Foundations of Computer Science undergraduate course

Expedite for Windows Software Development Kit Programming Guide

SQL Server Array Library László Dobos, Alexander S. Szalay

(!' ) "' # "*# "!(!' +,

SYSTEMS OF EQUATIONS AND MATRICES WITH THE TI-89. by Joseph Collison

R Language Definition

Making TIFF and EPS files from Drawing, Word Processing, PowerPoint and Graphing Programs

Habanero Extreme Scale Software Research Project

Using AllJoyn with Apache Cordova, Python & Node

Study of a neural network-based system for stability augmentation of an airplane

File Management Where did it go? Teachers College Summer Workshop

6. Cholesky factorization

Introduction to Matlab

Factoring. Factoring Polynomial Equations. Special Factoring Patterns. Factoring. Special Factoring Patterns. Special Factoring Patterns

Visual Basic Programming. An Introduction

rm(list=ls()) library(sqldf) system.time({large = read.csv.sql("large.csv")}) # seconds, 4.23GB of memory used by R

Lecture 12 Doubly Linked Lists (with Recursion)

An Introduction To The Web File Manager

How to start with 3DHOP

Ansur Test Executive. Users Manual

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Almost all spreadsheet programs are based on a simple concept: the malleable matrix.

MATLAB Tutorial. Chapter 6. Writing and calling functions

1 Posix API vs Windows API


EASRestoreService. Manual

MATLAB Instrument Driver

CMPT 373 Software Development Methods. Building Software. Nick Sumner Some materials from Shlomi Fish & Kitware

How To Write Portable Programs In C

Your Best Next Business Solution Big Data In R 24/3/2010

Internet Payment Gateway. Win32 API Developer Guide

HOW-TO. Access Data using BCI. Brian Leach Consulting Limited.

Using Files as Input/Output in Java 5.0 Applications

Creating and Viewing Task Dependencies between Multiple Projects using Microsoft Project

Linear Codes. Chapter Basics

The Union-Find Problem Kruskal s algorithm for finding an MST presented us with a problem in data-structure design. As we looked at each edge,

University of Hull Department of Computer Science. Wrestling with Python Week 01 Playing with Python

Create a New Database in Access 2010

SmartArrays and Java Frequently Asked Questions

PostgreSQL Functions By Example

COSC 6397 Big Data Analytics. Mahout and 3 rd homework assignment. Edgar Gabriel Spring Mahout

G563 Quantitative Paleontology. SQL databases. An introduction. Department of Geological Sciences Indiana University. (c) 2012, P.

Lecture 11 Doubly Linked Lists & Array of Linked Lists. Doubly Linked Lists

Bachelors of Computer Application Programming Principle & Algorithm (BCA-S102T)

Bypassing Memory Protections: The Future of Exploitation

Coding conventions and C++-style

Quiz 4 Solutions EECS 211: FUNDAMENTALS OF COMPUTER PROGRAMMING II. 1 Q u i z 4 S o l u t i o n s

A Comparison of C, MATLAB, and Python as Teaching Languages in Engineering

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Sources: On the Web: Slides will be available on:

Package GEOquery. August 18, 2015

Using Excel to find Perimeter, Area & Volume

Java from a C perspective. Plan

Abstract: We describe the beautiful LU factorization of a square matrix (or how to write Gaussian elimination in terms of matrix multiplication).

Using IRDB in a Dot Net Project

Stack Allocation. Run-Time Data Structures. Static Structures

Object-Oriented Programming in Java

Appendix: Tutorial Introduction to MATLAB

10CS35: Data Structures Using C

sqlite driver manual

Teldat Router. DNS Client

Input Output. 9.1 Why an IO Module is Needed? Chapter 9

Excel & Visual Basic for Applications (VBA)

CATIA V5 Tutorials. Mechanism Design & Animation. Release 18. Nader G. Zamani. University of Windsor. Jonathan M. Weaver. University of Detroit Mercy

Using C to Access Data Stored in Program Memory on the TMS320C54x DSP

Programming Database lectures for mathema

umps software development

Transcription:

Brian Caffo Using.Call in R

R s.call Interface to C.Call is a suped up version of.c Pass R objects to C Create R objects in C Manipulate R objects in C Return R objects from C Call R functions from C The Writing R Extensions manual is the definative source of information about.call The manual suggests trying to write native R code first, then use.c then try.call

Learning.Call You will only learn to use.call if you start and keep using it (as with all other topics in this class.) Read the Writing R Extensions manual over and over.external is another interface which does not seem as popular within the department Today we ll talk about using.call in generic R code, using it while creating a package introduces minor changes Using.Call in Microsoft Windows is easy, but requires some tinkering. See Duncan Murdoch s web page about compiling R on Windows for more information.

Running.Call.Call requires A C function, say mycfunc.c The C function to be compiled via R CMD SHLIB, which creates the object code mycfunc.o and the dll mycfunc.so The dll to be loaded into R, say with dyn.load("mycfunc.so") A.Call statement.call("myfunc", arguments) I almost always use the naming convention: one C function per file, the filename is the function name plus.c I get tired of typing R CMD SHLIB alias Rcs="R CMD SHLIB"

Header Files R has several utility header files that you should include #include <R.h> #include <Rinternals.h> #include <Rmath.h>

An Example, Summing the Elements of a Vector In vecsum.c we have the header files plus SEXP vecsum(sexp Rvec){ int i, n; double *vec, value = 0; vec = REAL(Rvec); n = length(rvec); for (i = 0; i < n; i++) value += vec[i]; printf("the value is: %4.6f \n", value); return R_NilValue; }

Executing vecsum At the command line R CMD SHLIB vecsum.c which creates vecsum.o and vecsum.so In an R session > dyn.load("vecsum.so") >.Call("vecSum", rnorm(10)) The value is: 3.230545 NULL >

Some details SEXP is a structure defined by the R gurus. expression It stands for S Functions to be used with.call should accept and return SEXP If you don t want your function to return anything use return R_NilValue The statement vec = REAL(Rvec); defines a pointer to the real part of Rvec This is useful so we can type vec[0] instead of REAL(Rvec)[0] (Remember since vec is a pointer, changes to it change Rvec)

Error checking and type coercion You should do error checking and type coercion You can do this in your C function or in an R function wrapper (I find it easier to do it in R) Example vecsum <- function(vec){ if (!is.vector(vec)) stop("vec must be a vector") if (!is.real(vec)) vec <- as.real(vec).call("vecsum", vec) }

Defining and returning a new SEXP Write a C program, ab.c that returns a vector of the numbers from a to b Coerce possibly real arguments a and b into integers in the C code Create and return an S expression Use PROTECT and UNPROTECT

The C code In ab.c we have the header files plus SEXP ab(sexp Ra, SEXP Rb){ int i, a, b; SEXP Rval; Ra = coercevector(ra, INTSXP); Rb = coercevector(rb, INTSXP); a = INTEGER(Ra)[0]; b = INTEGER(Rb)[0]; PROTECT(Rval = allocvector(intsxp, b - a + 1)); for (i = a; i <= b; i++) INTEGER(Rval)[i - a] = i; UNPROTECT(1); return Rval; }

In an R session > dyn.load("ab.so") >.Call("ab", 1, 5) [1] 1 2 3 4 5 >

Another example Create a function that returns upper triangular matrix SEXP uptri(sexp RinMatrix) Get the dimensions of the input matrix Rdim = getattrib(rinmatrix, R_DimSymbol); I = INTEGER(Rdim)[0]; J = INTEGER(Rdim)[1]; Do some error checking and coerce to real if (I!= J) error("input must be a square matrix"); RinMatrix = coercevector(rinmatrix, REALSXP);

More code for uptri Allocate the memory for the returned matrix PROTECT(Rval = allocmatrix(realsxp, I, J)); Set it s values for (i = 0; i < I; i++) for (j = 0; j < I; j++) if (i <= j) REAL(Rval)[i + I * j] = REAL(RinMatrix)[i + I * j]; else REAL(Rval)[i + I * j] = 0; Return it UNPROTECT(1); return Rval;

Here s what you get > dyn.load("uptri.so") > tmp <- matrix(1 : 4, 2, 2) > tmp [,1] [,2] [1,] 1 3 [2,] 2 4 >.Call("upTri", tmp) [,1] [,2] [1,] 1 3 [2,] 0 4 > Ahhhhhhhhhh, now we never have to deal with those pesky lower diagonal elements again. (Of course, R already has a function to do this.)

Final Thoughts You can read in, create and return lists using.call You can get and set attributes such as rownames, dimnames etcetera You can call R functions in your C code We used vector allocation methods from Rinternals.h, alternative methods from Rdefines.h can also be used Look over path to R/src/include/Rinternals.h when you need to know how/if something is defined It s almost always better to write a slow version in native R first before trying any C code