This document introduces the .C and .Call interfaces in R for calling C routines. The .C interface allows passing arguments between R and C functions, while .Call allows more flexibility in manipulating R objects in C code. An example comparing R, compiled R, and C implementations of generating a covariance matrix is provided to demonstrate the interfaces. Important header files, data types, and functions for using .C and .Call in C code are also outlined.
R is an open source statistical programming language developed from S at the University of Auckland in 1993. It is dynamically typed and treats vectors as first-class objects. Functions in R are also objects that can be assigned to variables. R has various options for binding scalars and vectors together into arrays and data frames for aggregate analysis. It also includes many built-in functions for numerical, statistical, and character manipulation of data.
This document contains Prof. A. Syed Mustafa's answers to a model question paper for the Programming in C and Data Structures course. It includes answers to questions on C variable names, the printf statement, finding the area of a triangle using Heron's formula, determining the size of data types using sizeof, relational and logical operators in C, nested if-else statements, finding the largest of three numbers, do-while loops and calculating factorials, finding the GCD of two numbers using a ternary operator and for loop, and a basic calculator program using a switch statement.
The document provides an overview of the C standard library. It includes a table listing common C standard library header files and briefly describing their purpose, such as <stdio.h> for input/output functions and <stdlib.h> for memory allocation and process control. The C standard library contains functions for tasks like string manipulation, mathematics, random numbers, memory management and more. It provides a standard library that is common across C implementations.
VTU 1ST SEM PROGRAMMING IN C & DATA STRUCTURES SOLVED PAPERS OF JUNE-2015 & ...vtunotesbysree
The document contains solved question papers from June 2015 and December 2015 for Programming in C & Data Structures examinations. It includes questions ranging from basic C programming concepts like data types, operators, decision making and looping statements to more advanced topics such as arrays, strings, structures, files and pointers. For each question, the relevant concept is explained and examples are provided. Solutions for some programming problems involving simple calculations, palindrome checks and file handling are also presented.
This document provides an overview of the C programming language. It discusses the origins and development of C from the B programming language. Some key features and benefits of C discussed include its low-level capabilities as a second-generation language, structured programming approach, use of functions and libraries, and support for pointers, memory allocation, recursion, and bit manipulation. The document also covers C's fundamental and derived data types, defining variables and strings, and the structure of C functions including single-level functions.
A parser is a program component that breaks input data into smaller elements according to the rules of a formal grammar. It builds a parse tree representing the syntactic structure of the input based on these grammar rules. There are two main types of parsers: top-down parsers start at the root of the parse tree and work downward, while bottom-up parsers start at the leaves and work upward. Parser generators use attributes like First and Follow to build parsing tables for predictive parsers like LL(1) parsers, which parse input from left to right based on a single lookahead token.
Detecting Occurrences of Refactoring with Heuristic SearchShinpei Hayashi
This document describes a technique for detecting refactorings between two versions of a program using heuristic search. Refactorings are detected by generating intermediate program states through applying refactorings, and finding a path from the original to modified program that minimizes differences. Structural differences are used to identify likely refactorings. Candidate refactorings are evaluated and applied to generate new states, with the search terminating when the state matches the modified program. A supporting tool was developed and a case study found the technique could correctly detect an actual series of refactorings between program versions.
This is Work-In-Progress. Developing a series of lectures on C++0x. This will augment my presentations on C++ and Design Pattern. First trial run was done at Interra, Noida in 2009
R is an open source statistical programming language developed from S at the University of Auckland in 1993. It is dynamically typed and treats vectors as first-class objects. Functions in R are also objects that can be assigned to variables. R has various options for binding scalars and vectors together into arrays and data frames for aggregate analysis. It also includes many built-in functions for numerical, statistical, and character manipulation of data.
This document contains Prof. A. Syed Mustafa's answers to a model question paper for the Programming in C and Data Structures course. It includes answers to questions on C variable names, the printf statement, finding the area of a triangle using Heron's formula, determining the size of data types using sizeof, relational and logical operators in C, nested if-else statements, finding the largest of three numbers, do-while loops and calculating factorials, finding the GCD of two numbers using a ternary operator and for loop, and a basic calculator program using a switch statement.
The document provides an overview of the C standard library. It includes a table listing common C standard library header files and briefly describing their purpose, such as <stdio.h> for input/output functions and <stdlib.h> for memory allocation and process control. The C standard library contains functions for tasks like string manipulation, mathematics, random numbers, memory management and more. It provides a standard library that is common across C implementations.
VTU 1ST SEM PROGRAMMING IN C & DATA STRUCTURES SOLVED PAPERS OF JUNE-2015 & ...vtunotesbysree
The document contains solved question papers from June 2015 and December 2015 for Programming in C & Data Structures examinations. It includes questions ranging from basic C programming concepts like data types, operators, decision making and looping statements to more advanced topics such as arrays, strings, structures, files and pointers. For each question, the relevant concept is explained and examples are provided. Solutions for some programming problems involving simple calculations, palindrome checks and file handling are also presented.
This document provides an overview of the C programming language. It discusses the origins and development of C from the B programming language. Some key features and benefits of C discussed include its low-level capabilities as a second-generation language, structured programming approach, use of functions and libraries, and support for pointers, memory allocation, recursion, and bit manipulation. The document also covers C's fundamental and derived data types, defining variables and strings, and the structure of C functions including single-level functions.
A parser is a program component that breaks input data into smaller elements according to the rules of a formal grammar. It builds a parse tree representing the syntactic structure of the input based on these grammar rules. There are two main types of parsers: top-down parsers start at the root of the parse tree and work downward, while bottom-up parsers start at the leaves and work upward. Parser generators use attributes like First and Follow to build parsing tables for predictive parsers like LL(1) parsers, which parse input from left to right based on a single lookahead token.
Detecting Occurrences of Refactoring with Heuristic SearchShinpei Hayashi
This document describes a technique for detecting refactorings between two versions of a program using heuristic search. Refactorings are detected by generating intermediate program states through applying refactorings, and finding a path from the original to modified program that minimizes differences. Structural differences are used to identify likely refactorings. Candidate refactorings are evaluated and applied to generate new states, with the search terminating when the state matches the modified program. A supporting tool was developed and a case study found the technique could correctly detect an actual series of refactorings between program versions.
This is Work-In-Progress. Developing a series of lectures on C++0x. This will augment my presentations on C++ and Design Pattern. First trial run was done at Interra, Noida in 2009
This document summarizes key topics in intermediate code generation discussed in Chapter 6, including:
1) Variants of syntax trees like DAGs are introduced to share common subexpressions. Three-address code is also discussed where each instruction has at most three operands.
2) Type checking and type expressions are covered, along with translating expressions and statements to three-address code. Control flow statements like if/else are also translated using techniques like backpatching.
3) Backpatching allows symbolic labels in conditional jumps to be resolved by a later pass that inserts actual addresses, avoiding an extra pass. This and other control flow translation topics are covered.
This document discusses backpatching and syntax-directed translation for boolean expressions and flow-of-control statements. It describes using three functions - Makelist, Marklist, and Backpatch - to generate code with backpatching during a single pass. Boolean expressions are translated by constructing syntax trees and associating semantic actions to record quadruple indices for later backpatching. Flow-of-control statements like IF and WHILE are handled similarly, using marker nonterminals to record quadruple numbers for backpatching statement lists.
The document describes intermediate code generation during compilation.
1) An intermediate language is used to translate source programs into a form that is CPU independent yet close to machine language. This facilitates code optimization and retargeting of compilers.
2) Common intermediate languages include syntax trees, postfix notation, and three-address code using quadruples. Three-address code breaks down expressions into single assignment statements to simplify optimization.
3) Semantic rules for syntax-directed translation are described to generate three-address code for expressions, assignments, procedures, and other language constructs. Attributes track temporary variables and generated code.
Sentence-to-Code Traceability Recovery with Domain OntologiesShinpei Hayashi
The document describes a technique for recovering traceability between natural language sentences and source code using domain ontologies. An automated tool was implemented and evaluated on a case study using the JDraw software. Results showed the technique worked well, recovering traceability between 7 sentences and code with higher accuracy than without using the ontology. The ontology helped improve recall and detect traceability in cases where word similarity alone did not work well. Future work is needed to evaluate on larger cases and domains.
The document describes code generation for two commercial compilers:
1) The Borland C 3.0 compiler for the 80X86 generates assembly code using static simulation and frame pointers for function calls and local variable access.
2) The Sun 2.0 compiler for SPARCstations uses register-based calling conventions and generates efficient SPARC assembly code.
Both compilers handle code generation for arithmetic expressions, arrays, structures, pointers, control flow, and function calls.
The document discusses intermediate code generation in compilers. It describes how compilers generate intermediate code representations after parsing source code. Intermediate representations allow separating the front-end and back-end of compilers, facilitating code optimization and retargeting compilers to different architectures. Common intermediate representations discussed include abstract syntax trees, postfix notation, static single assignment form, and three-address instructions. The document also provides examples of generating three-address code using syntax-directed translation.
A parser breaks down input into smaller elements for translation into another language. It takes a sequence of tokens as input and builds a parse tree or abstract syntax tree. In the compiler model, the parser verifies that the token string can be generated by the grammar and returns any syntax errors. There are two main types of parsers: top-down parsers start at the root and fill in the tree, while bottom-up parsers start at the leaves and work upwards. Syntax directed definitions associate attributes with grammar symbols and specify attribute values with semantic rules for each production.
C Programming Language Tutorial for beginners - JavaTpointJavaTpoint.Com
JavaTpoint share a presentation of C Programming language for beginners and professionals. now in this slideshare you will be learned basics of c programming language, what is c programming language, history of c programming, installing turbo c, features of c programming language, datatypes of c language, operaters in c, control statement of c language, c language functions, c array, pointer in c programming, and structure and union.
Object-Oriented Programming in Modern C++. Borislav Stanimirov. CoreHard Spri...corehard_by
Object-oriented programming has been criticized a lot. Every now and then some article or talk appears denouncing it and proclaiming that it's dead. This talk will do the opposite. It defends OOP and presents many modern libraries and concepts to show that it's very much alive and kicking.
The document discusses intermediate code generation in compilers. It describes how compilers generate an intermediate representation from the abstract syntax tree that is machine independent and allows for optimizations. One popular intermediate representation is three-address code, where each statement contains at most three operands. This code is then represented using structures like quadruples and triples to store the operator and operands for code generation and rearranging during optimizations. Static single assignment form is also covered, which assigns unique names to variables to facilitate optimizations.
The document summarizes the history and key features of the C programming language. C was developed in the late 1960s and early 1970s at Bell Labs to be a high-level language that produced efficient machine code. It was designed to allow systems programming for operating systems and utilities. C borrowed elements from its predecessors BCPL and B but added data types, structures, unions, and functions to support structured programming.
Generating Assertion Code from OCL: A Transformational Approach Based on Simi...Shinpei Hayashi
This document presents an approach for generating assertion code from the Object Constraint Language (OCL) using model transformations. The approach constructs a hierarchy of programming languages based on their structural similarities. This allows rules for translating OCL to be reused across multiple implementation languages, saving approximately 50% of the effort compared to creating individual translators. An evaluation implemented the approach in Maude and demonstrated its ability to generate code for Java, Python, Haskell and O'Haskell from a single OCL specification.
This document discusses code generation in compilers. It covers:
- The code generator takes an intermediate representation and produces target code that is correct and efficient for the target machine.
- Symbol tables are used to track variable semantics, data types, scopes, and storage addresses. Common implementations are unordered lists and ordered linear lists.
- The target machine format can be absolute machine language, relocatable machine language, or assembly language. Memory management involves mapping names to runtime memory addresses.
- Basic blocks, control flow graphs, and structure-preserving transformations like common subexpression elimination are discussed for code optimization.
The program takes a number as input from the user, multiplies it by 10, and displays the result. It uses the printf() function to display text and the scanf() function to take input. The number input is stored in the variable number, multiplied by 10 and stored in the variable result, which is then printed along with an output message.
Download this Presentation for free from www.ecti.co.in/downloads.html
No SIGN UP REQUIRED.
C Programming Training PPTs / PDFs for free.
Download free C Programming study material. Learn C Programming for free in 2 hours.
This document provides an overview of the C programming language. It begins with an outline of topics covered, then discusses the history and development of C. Key features of C mentioned include its portability, speed, and ability to be extended by users. The document explains the role of compilers in converting C code to object code. It also includes examples of basic C programs and flowcharts, and covers C concepts like data types, variables, operators, and control structures. Overall, the document serves as an introduction to the C language, its history and basics.
C Programming Language Step by Step Part 1Rumman Ansari
This document provides an overview of the C programming language. It discusses the history and development of C, starting with predecessors like ALGOL-60 and BCPL in the 1960s and 1970s. C was created in the early 1970s and the first C compiler was released in 1978. Since then, C has become widely used for system programming and is foundational to many other languages like C++ and Java. The document outlines some key advantages of C, like its efficiency and ability to handle low-level tasks. It also provides brief descriptions of common C programming concepts.
This document provides 50 interview questions on C programming language organized into 5 chapters: Variables & Control Flow, Operators, Constants & Structures, Functions, Pointers, and Programs. It aims to help both freshers and experienced programmers quickly brush up on basic C concepts commonly asked during job interviews at top companies. Each question is accompanied by a detailed answer along with code examples where applicable. Feedback is welcomed to be sent to the publisher.
An introduction to the C programming language for the students of the course "HJ-82 Ontwerpen voor de optie multimedia en signaalverwerking: seminaries", taught by the authors at the Catholic University of Leuven.
This document provides information about Erasmus grants for students studying abroad in the EU. It outlines that Erasmus funds both work and study placements of a minimum 3 months, with an initial grant rate of EUR225 per month. Students must submit 5 forms to apply for funding, including details forms, agreements, and a final report. Funding is allocated in rounds starting in November, provided all application forms have been received. The document stresses that students should not rely on the grant alone and must notify the International Office of any changes to their placement period.
This document summarizes key topics in intermediate code generation discussed in Chapter 6, including:
1) Variants of syntax trees like DAGs are introduced to share common subexpressions. Three-address code is also discussed where each instruction has at most three operands.
2) Type checking and type expressions are covered, along with translating expressions and statements to three-address code. Control flow statements like if/else are also translated using techniques like backpatching.
3) Backpatching allows symbolic labels in conditional jumps to be resolved by a later pass that inserts actual addresses, avoiding an extra pass. This and other control flow translation topics are covered.
This document discusses backpatching and syntax-directed translation for boolean expressions and flow-of-control statements. It describes using three functions - Makelist, Marklist, and Backpatch - to generate code with backpatching during a single pass. Boolean expressions are translated by constructing syntax trees and associating semantic actions to record quadruple indices for later backpatching. Flow-of-control statements like IF and WHILE are handled similarly, using marker nonterminals to record quadruple numbers for backpatching statement lists.
The document describes intermediate code generation during compilation.
1) An intermediate language is used to translate source programs into a form that is CPU independent yet close to machine language. This facilitates code optimization and retargeting of compilers.
2) Common intermediate languages include syntax trees, postfix notation, and three-address code using quadruples. Three-address code breaks down expressions into single assignment statements to simplify optimization.
3) Semantic rules for syntax-directed translation are described to generate three-address code for expressions, assignments, procedures, and other language constructs. Attributes track temporary variables and generated code.
Sentence-to-Code Traceability Recovery with Domain OntologiesShinpei Hayashi
The document describes a technique for recovering traceability between natural language sentences and source code using domain ontologies. An automated tool was implemented and evaluated on a case study using the JDraw software. Results showed the technique worked well, recovering traceability between 7 sentences and code with higher accuracy than without using the ontology. The ontology helped improve recall and detect traceability in cases where word similarity alone did not work well. Future work is needed to evaluate on larger cases and domains.
The document describes code generation for two commercial compilers:
1) The Borland C 3.0 compiler for the 80X86 generates assembly code using static simulation and frame pointers for function calls and local variable access.
2) The Sun 2.0 compiler for SPARCstations uses register-based calling conventions and generates efficient SPARC assembly code.
Both compilers handle code generation for arithmetic expressions, arrays, structures, pointers, control flow, and function calls.
The document discusses intermediate code generation in compilers. It describes how compilers generate intermediate code representations after parsing source code. Intermediate representations allow separating the front-end and back-end of compilers, facilitating code optimization and retargeting compilers to different architectures. Common intermediate representations discussed include abstract syntax trees, postfix notation, static single assignment form, and three-address instructions. The document also provides examples of generating three-address code using syntax-directed translation.
A parser breaks down input into smaller elements for translation into another language. It takes a sequence of tokens as input and builds a parse tree or abstract syntax tree. In the compiler model, the parser verifies that the token string can be generated by the grammar and returns any syntax errors. There are two main types of parsers: top-down parsers start at the root and fill in the tree, while bottom-up parsers start at the leaves and work upwards. Syntax directed definitions associate attributes with grammar symbols and specify attribute values with semantic rules for each production.
C Programming Language Tutorial for beginners - JavaTpointJavaTpoint.Com
JavaTpoint share a presentation of C Programming language for beginners and professionals. now in this slideshare you will be learned basics of c programming language, what is c programming language, history of c programming, installing turbo c, features of c programming language, datatypes of c language, operaters in c, control statement of c language, c language functions, c array, pointer in c programming, and structure and union.
Object-Oriented Programming in Modern C++. Borislav Stanimirov. CoreHard Spri...corehard_by
Object-oriented programming has been criticized a lot. Every now and then some article or talk appears denouncing it and proclaiming that it's dead. This talk will do the opposite. It defends OOP and presents many modern libraries and concepts to show that it's very much alive and kicking.
The document discusses intermediate code generation in compilers. It describes how compilers generate an intermediate representation from the abstract syntax tree that is machine independent and allows for optimizations. One popular intermediate representation is three-address code, where each statement contains at most three operands. This code is then represented using structures like quadruples and triples to store the operator and operands for code generation and rearranging during optimizations. Static single assignment form is also covered, which assigns unique names to variables to facilitate optimizations.
The document summarizes the history and key features of the C programming language. C was developed in the late 1960s and early 1970s at Bell Labs to be a high-level language that produced efficient machine code. It was designed to allow systems programming for operating systems and utilities. C borrowed elements from its predecessors BCPL and B but added data types, structures, unions, and functions to support structured programming.
Generating Assertion Code from OCL: A Transformational Approach Based on Simi...Shinpei Hayashi
This document presents an approach for generating assertion code from the Object Constraint Language (OCL) using model transformations. The approach constructs a hierarchy of programming languages based on their structural similarities. This allows rules for translating OCL to be reused across multiple implementation languages, saving approximately 50% of the effort compared to creating individual translators. An evaluation implemented the approach in Maude and demonstrated its ability to generate code for Java, Python, Haskell and O'Haskell from a single OCL specification.
This document discusses code generation in compilers. It covers:
- The code generator takes an intermediate representation and produces target code that is correct and efficient for the target machine.
- Symbol tables are used to track variable semantics, data types, scopes, and storage addresses. Common implementations are unordered lists and ordered linear lists.
- The target machine format can be absolute machine language, relocatable machine language, or assembly language. Memory management involves mapping names to runtime memory addresses.
- Basic blocks, control flow graphs, and structure-preserving transformations like common subexpression elimination are discussed for code optimization.
The program takes a number as input from the user, multiplies it by 10, and displays the result. It uses the printf() function to display text and the scanf() function to take input. The number input is stored in the variable number, multiplied by 10 and stored in the variable result, which is then printed along with an output message.
Download this Presentation for free from www.ecti.co.in/downloads.html
No SIGN UP REQUIRED.
C Programming Training PPTs / PDFs for free.
Download free C Programming study material. Learn C Programming for free in 2 hours.
This document provides an overview of the C programming language. It begins with an outline of topics covered, then discusses the history and development of C. Key features of C mentioned include its portability, speed, and ability to be extended by users. The document explains the role of compilers in converting C code to object code. It also includes examples of basic C programs and flowcharts, and covers C concepts like data types, variables, operators, and control structures. Overall, the document serves as an introduction to the C language, its history and basics.
C Programming Language Step by Step Part 1Rumman Ansari
This document provides an overview of the C programming language. It discusses the history and development of C, starting with predecessors like ALGOL-60 and BCPL in the 1960s and 1970s. C was created in the early 1970s and the first C compiler was released in 1978. Since then, C has become widely used for system programming and is foundational to many other languages like C++ and Java. The document outlines some key advantages of C, like its efficiency and ability to handle low-level tasks. It also provides brief descriptions of common C programming concepts.
This document provides 50 interview questions on C programming language organized into 5 chapters: Variables & Control Flow, Operators, Constants & Structures, Functions, Pointers, and Programs. It aims to help both freshers and experienced programmers quickly brush up on basic C concepts commonly asked during job interviews at top companies. Each question is accompanied by a detailed answer along with code examples where applicable. Feedback is welcomed to be sent to the publisher.
An introduction to the C programming language for the students of the course "HJ-82 Ontwerpen voor de optie multimedia en signaalverwerking: seminaries", taught by the authors at the Catholic University of Leuven.
This document provides information about Erasmus grants for students studying abroad in the EU. It outlines that Erasmus funds both work and study placements of a minimum 3 months, with an initial grant rate of EUR225 per month. Students must submit 5 forms to apply for funding, including details forms, agreements, and a final report. Funding is allocated in rounds starting in November, provided all application forms have been received. The document stresses that students should not rely on the grant alone and must notify the International Office of any changes to their placement period.
SAB 410 Cristal Concentrate is a waterproofing and protective system for concrete that works through internal crystallization. It penetrates pores, capillaries and cracks up to 0.25mm wide, forming crystals that block water penetration. Independent of water pressure, it forms crystals that block water over time. It can be applied to structures like reservoirs, tunnels, and foundations to waterproof and protect against degradation. It has low vapor permeability, penetrates deeply, and maintains water-tightness even if the surface is damaged.
The document provides guidance on assessing your interests and goals for graduate school, selecting the right program, and navigating the application process. It discusses essential application materials like resumes, letters of recommendation, essays, and test scores. Additionally, it offers advice on financing options for graduate degrees such as assistantships, fellowships, grants, loans, and employment opportunities.
The document discusses infographics and provides tips for designing them. It defines infographics as visual representations of data or information. It then describes different types of infographics like statistical charts, timelines, and process diagrams. The document evaluates sample infographics and provides design tips such as making the graphic concise, visual, easy to understand, accurate, attractive, and creative. It stresses citing sources and conveying information visually.
This document discusses how our thoughts influence our feelings and actions, which ultimately shape our results. It emphasizes that we have the potential to achieve success by changing our thinking. Specifically, it notes that we must filter external influences, consciously choose to believe in our dreams, internalize our dreams to feel positive about them, and take action in order to realize results. The overarching message is that we determine our outcomes through our mindset.
Jadwal acara Khanduri Pilem menayangkan berbagai film Indonesia dari 18-21 April 2014. Film pertama yang ditayangkan adalah drama Cahaya yang menceritakan perjalanan seorang gadis mencari ayahnya di Jakarta. Film-film pendek mutakhir Indonesia juga diputar seperti Vulgar yang menceritakan tiga santri yang keluar dari pesantren di malam hari. Karya-karya sutradara Edwin seperti A Very Slow Breakfast dan Kara, Anak Sebatang Poh
Dokumen tersebut membahas tentang pengadaan pegawai negeri sipil (PNS) mulai dari proses rekrutmen, seleksi, penetapan pelamar yang lulus, hingga pelaporan dan pembiayaan pengadaan PNS. Proses pengadaan PNS harus dilakukan secara transparan, akuntabel, dan berdasarkan kompetensi pelamar.
Dokumen tersebut membahas tentang masalah akses kesehatan bagi masyarakat miskin di Indonesia. Program Jaminan Kesehatan Masyarakat (JAMKESMAS) yang diciptakan pemerintah untuk menjamin akses kesehatan gratis bagi masyarakat miskin masih mengalami berbagai hambatan pelaksanaan seperti data peserta yang kurang akurat dan kualitas pelayanan yang masih buruk.
Dokumen tersebut membahas tentang konteks dasar sistem pemerintahan Indonesia yang terdiri dari bagian-bagian yang saling berkaitan untuk mencapai tujuan tertentu, serta penjelasan mengenai teori-teori dasar pemerintahan seperti pemisahan kekuasaan, demokrasi, negara berdasarkan atas hukum, dan negara berkonstitusi.
Sistem politik di Indonesia adalah demokrasi berdasarkan Pancasila yang menerapkan kedaulatan rakyat melalui perwakilan. Sistem ini terdiri atas struktur politik seperti lembaga legislatif, eksekutif, dan yudikatif serta infrastruktur seperti partai politik dan organisasi masyarakat. Rakyat dapat berpartisipasi secara konvensional maupun non-konvensional dalam sistem politik ini.
Presentation on native interfaces for the R programming language given as part of a course in advanced R programming at FHCRC:
https://secure.bioconductor.org/SeattleMay10/
Integrating R with C++: Rcpp, RInside and RProtoBufRomain Francois
This document discusses integrating R with C++ using Rcpp, RInside and RProtoBuf. It provides an overview of the R API and how R supports C/C++. It then describes the key features of Rcpp, including encapsulating R objects in C++ classes, conversion between R and C++ types, and using the Rcpp API to write efficient C++ functions that integrate seamlessly with R. Examples are provided to illustrate calculating a density estimate, working with environments and lists, and using STL algorithms like std::transform to write a C++ version of lapply.
This document provides an introduction and overview of R programming for statistics. It discusses how to run R sessions and functions, basic math operations and data types in R like vectors, data frames, and matrices. It also covers statistical and graphical features of R, programming features like functions, and gives examples of built-in and user-defined functions.
R is a widely used programming language for statistical analysis and graphics. It allows integration with other languages like C/C++ for efficiency. R includes features like conditionals, loops, functions, and data handling capabilities. It supports various data types including vectors, lists, matrices, arrays, factors and data frames. Variables can be assigned values and their data type changed. Operators include arithmetic, relational, logical and assignment operators. Functions are objects that perform specific tasks and are called with arguments. Strings are stored within double quotes. Vectors are basic data objects that can have single or multiple elements.
What is Relational model
Characteristics
Relational constraints
Representation of schemas
characteristics and Constraints of Relational model with proper examples.
Updates and dealing with constraint violations in Relational model
I am Gozan. M. I am a Programming Exam Helper at liveexamhelper.com. I hold a master' Degree in Programming from the University of Denver, USA. I have been helping students with their exams for the past 9 years. You can hire me to take your exam in Programming. Visit liveexamhelper.com or email info@liveexamhelper.com. You can also call on +1 678 648 4277 for any assistance with the Programming Exam.
The presentation is a brief case study of R Programming Language. In this, we discussed the scope of R, Uses of R, Advantages and Disadvantages of the R programming Language.
Rcpp provides seamless integration between R and C++. It includes an API that encapsulates R objects in C++ classes and allows for conversion between R and C++ types. Rcpp sugar extends this by providing R-like syntax in C++, such as ifelse statements, to make C++ code more readable and consistent with R code. This allows leveraging of C++ capabilities while retaining an R-like syntax.
Best corporate-r-programming-training-in-mumbaiUnmesh Baile
Vibrant Technologies is headquarted in Mumbai,India.We are the best Teradata training provider in Navi Mumbai who provides Live Projects to students.We provide Corporate Training also.We are Best Teradata Database classes in Mumbai according to our students and corporates
This document provides an overview of the R programming language and environment. It discusses why R is useful, outlines its interface and workspace, describes how to access help and tutorials, install packages, and input/output data. The interactive nature of R is highlighted, where results from one function can be used as input for another.
Rcpp provides seamless integration between R and C++. It includes the Rcpp API for wrapping R objects in C++ and converting between R and C++ types, Rcpp sugar for adding R-like syntax to C++, and Rcpp modules for exposing C++ classes and functions to R. The presentation provided examples of using the Rcpp API and sugar to write C++ functions that integrate with R. It also demonstrated how to define C++ modules to expose classes and functions to R. Benchmarks showed that Rcpp sugar can provide significant performance gains over the base R API.
This document provides an introduction and overview of the R programming language. It discusses installing R, using the R console and script editor, finding documentation, and some basic features. The key points covered are what R is, how to install packages, using the console as a calculator, assigning objects and calling functions, commenting code in scripts, and where to find documentation on functions.
This document provides an overview of the C programming language. It discusses that C was developed in 1972 at Bell Labs and is a popular systems and applications programming language. The document then covers various C language concepts like data types, variables, operators, input/output functions, and provides examples of basic C programs and code snippets.
R is a programming language and free software environment for statistical analysis and graphics. It is widely used among statisticians and data scientists for developing statistical software and data analysis. Some key facts about R:
- It was created in the 1990s by Ross Ihaka and Robert Gentleman at the University of Auckland.
- R can be used for statistical computing, machine learning, graphical display, and other tasks related to data analysis.
- It runs on Windows, Linux, and MacOS operating systems. Code written in R is cross-platform.
- R has a large collection of statistical and graphical techniques built-in, and users can extend its capabilities by downloading additional packages.
- Major
This document discusses different programming paradigms including procedural, object-oriented, and declarative paradigms. It provides examples of code using these paradigms. Specifically, it shows an assembly language program that adds two numbers, a C++ program that calculates the area of a rectangle, and Prolog queries to retrieve information from a database about people's genders and family relationships. It also discusses how parameters are used to pass values to functions in Visual Basic.
R is a free and open-source programming language and software environment for statistical analysis, graphics, and statistical computing. It was originally developed in the 1990s at Bell Laboratories by statisticians John Chambers and colleagues. Key points about R include that it is an interpreted language, supports functional programming, and is object-oriented. R can be used for tasks like statistical analysis, data visualization, and machine learning. It has a large community of users and developers contributing packages for specialized analysis techniques.
Compiler Design lab manual for Computer Engineering .pdfkalpana Manudhane
Compiler Design can be divided into two parts: analysis and synthesis. The analysis part breaks up the source program into constituent pieces and imposes a grammatical structure on them. The synthesis part constructs the desired target program from the intermediate representation and the information in the symbol table. If we examine the compilation process in more detail, we see that it operates as a sequence of phases-lexical analysis, syntax & semantic analysis, intermediate code generation, code optimization & code generation, each of which transforms one representation of the source program to another.
Practical of Compiler Design Lab for Computer Science & Engineering are divided into two parts- i) implementation using programming language and ii) implementation using tools. In first part, practical can be performed in any programming language such as C language or Python. C language is always preferred. C is the middle level language combining low-level hardware controlling ability and high level programming capabilities. It is the procedural language focusing on functions and pointers.
To implement phases of compiler, various tools are available in Linux system. Lex tool is lexical analyzer generator whereas YACC tool is parser generator. Recent versions of Lex and YACC tools are Flex and Bison respectively. Recently windows version of these tools is available. Flex Windows (Lex and Yacc) contains the GNU Win 32 Ports of Flex and Bison, which are Lex and Yacc Compilers respectively, and are used for generating tokens and parsers.
This individual assignment submission contains code snippets and explanations for various Python programming concepts and techniques. It includes programs to prompt a user for input, calculate pay and grades, define functions, use data types like lists and dictionaries, and work with classes and objects. The submission also contains questions about Python concepts like loops, variables, modules, file handling, and database usage. Overall, the document demonstrates an understanding of core Python programming and problem-solving skills.
R is a programming language and software environment for statistical analysis and graphics. It was created by Ross Ihaka and Robert Gentleman in the early 1990s at the University of Auckland, New Zealand. Some key points:
- R can be used for statistical computing, machine learning, and data analysis. It is widely used among statisticians and data scientists.
- It runs on Windows, Mac OS, and Linux. The source code is published under the GNU GPL license.
- Popular companies like Facebook, Google, Microsoft, Uber and Airbnb use R for data analysis, machine learning, and statistical computing.
- R has a variety of data structures like vectors, matrices, arrays, lists
The document contains 40 multiple choice questions related to computer science class 12. It covers topics like variables, data types, operators, loops, functions, arrays and more. The questions test concepts like escape sequences, format specifiers, assignment operators, comments, input/output functions, and the difference between various loops in C programming language. It is a practice test to help students prepare for their computer science exam.
Strategies for Effective Upskilling is a presentation by Chinwendu Peace in a Your Skill Boost Masterclass organisation by the Excellence Foundation for South Sudan on 08th and 09th June 2024 from 1 PM to 3 PM on each day.
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UPRAHUL
This Dissertation explores the particular circumstances of Mirzapur, a region located in the
core of India. Mirzapur, with its varied terrains and abundant biodiversity, offers an optimal
environment for investigating the changes in vegetation cover dynamics. Our study utilizes
advanced technologies such as GIS (Geographic Information Systems) and Remote sensing to
analyze the transformations that have taken place over the course of a decade.
The complex relationship between human activities and the environment has been the focus
of extensive research and worry. As the global community grapples with swift urbanization,
population expansion, and economic progress, the effects on natural ecosystems are becoming
more evident. A crucial element of this impact is the alteration of vegetation cover, which plays a
significant role in maintaining the ecological equilibrium of our planet.Land serves as the foundation for all human activities and provides the necessary materials for
these activities. As the most crucial natural resource, its utilization by humans results in different
'Land uses,' which are determined by both human activities and the physical characteristics of the
land.
The utilization of land is impacted by human needs and environmental factors. In countries
like India, rapid population growth and the emphasis on extensive resource exploitation can lead
to significant land degradation, adversely affecting the region's land cover.
Therefore, human intervention has significantly influenced land use patterns over many
centuries, evolving its structure over time and space. In the present era, these changes have
accelerated due to factors such as agriculture and urbanization. Information regarding land use and
cover is essential for various planning and management tasks related to the Earth's surface,
providing crucial environmental data for scientific, resource management, policy purposes, and
diverse human activities.
Accurate understanding of land use and cover is imperative for the development planning
of any area. Consequently, a wide range of professionals, including earth system scientists, land
and water managers, and urban planners, are interested in obtaining data on land use and cover
changes, conversion trends, and other related patterns. The spatial dimensions of land use and
cover support policymakers and scientists in making well-informed decisions, as alterations in
these patterns indicate shifts in economic and social conditions. Monitoring such changes with the
help of Advanced technologies like Remote Sensing and Geographic Information Systems is
crucial for coordinated efforts across different administrative levels. Advanced technologies like
Remote Sensing and Geographic Information Systems
9
Changes in vegetation cover refer to variations in the distribution, composition, and overall
structure of plant communities across different temporal and spatial scales. These changes can
occur natural.
How to Setup Warehouse & Location in Odoo 17 InventoryCeline George
In this slide, we'll explore how to set up warehouses and locations in Odoo 17 Inventory. This will help us manage our stock effectively, track inventory levels, and streamline warehouse operations.
Temple of Asclepius in Thrace. Excavation resultsKrassimira Luka
The temple and the sanctuary around were dedicated to Asklepios Zmidrenus. This name has been known since 1875 when an inscription dedicated to him was discovered in Rome. The inscription is dated in 227 AD and was left by soldiers originating from the city of Philippopolis (modern Plovdiv).
Walmart Business+ and Spark Good for Nonprofits.pdfTechSoup
"Learn about all the ways Walmart supports nonprofit organizations.
You will hear from Liz Willett, the Head of Nonprofits, and hear about what Walmart is doing to help nonprofits, including Walmart Business and Spark Good. Walmart Business+ is a new offer for nonprofits that offers discounts and also streamlines nonprofits order and expense tracking, saving time and money.
The webinar may also give some examples on how nonprofits can best leverage Walmart Business+.
The event will cover the following::
Walmart Business + (https://business.walmart.com/plus) is a new shopping experience for nonprofits, schools, and local business customers that connects an exclusive online shopping experience to stores. Benefits include free delivery and shipping, a 'Spend Analytics” feature, special discounts, deals and tax-exempt shopping.
Special TechSoup offer for a free 180 days membership, and up to $150 in discounts on eligible orders.
Spark Good (walmart.com/sparkgood) is a charitable platform that enables nonprofits to receive donations directly from customers and associates.
Answers about how you can do more with Walmart!"
Leveraging Generative AI to Drive Nonprofit InnovationTechSoup
In this webinar, participants learned how to utilize Generative AI to streamline operations and elevate member engagement. Amazon Web Service experts provided a customer specific use cases and dived into low/no-code tools that are quick and easy to deploy through Amazon Web Service (AWS.)
Main Java[All of the Base Concepts}.docxadhitya5119
This is part 1 of my Java Learning Journey. This Contains Custom methods, classes, constructors, packages, multithreading , try- catch block, finally block and more.
हिंदी वर्णमाला पीपीटी, hindi alphabet PPT presentation, hindi varnamala PPT, Hindi Varnamala pdf, हिंदी स्वर, हिंदी व्यंजन, sikhiye hindi varnmala, dr. mulla adam ali, hindi language and literature, hindi alphabet with drawing, hindi alphabet pdf, hindi varnamala for childrens, hindi language, hindi varnamala practice for kids, https://www.drmullaadamali.com
This document provides an overview of wound healing, its functions, stages, mechanisms, factors affecting it, and complications.
A wound is a break in the integrity of the skin or tissues, which may be associated with disruption of the structure and function.
Healing is the body’s response to injury in an attempt to restore normal structure and functions.
Healing can occur in two ways: Regeneration and Repair
There are 4 phases of wound healing: hemostasis, inflammation, proliferation, and remodeling. This document also describes the mechanism of wound healing. Factors that affect healing include infection, uncontrolled diabetes, poor nutrition, age, anemia, the presence of foreign bodies, etc.
Complications of wound healing like infection, hyperpigmentation of scar, contractures, and keloid formation.
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptxEduSkills OECD
Iván Bornacelly, Policy Analyst at the OECD Centre for Skills, OECD, presents at the webinar 'Tackling job market gaps with a skills-first approach' on 12 June 2024
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
Dot Call interface
1. Introduction to .Call interface
Hao Chai
Department of Statistics and Actuarial Science
The University of Iowa
Productive Seminar
March 6, 2012
Hao Chai (U of Iowa) Introduction to .Call interface 1 / 41
2. Outline
1 Introduction
2 C part
.C interface
.Call interface
3 R part
4 Examples
5 Other
Hao Chai (U of Iowa) Introduction to .Call interface 2 / 41
3. Introduction
Outline
1 Introduction
2 C part
.C interface
.Call interface
3 R part
4 Examples
5 Other
Hao Chai (U of Iowa) Introduction to .Call interface 3 / 41
4. Introduction
.C and .Call are two interfaces in R to call C routines. Similar foreign
language interface functions are .Fortran and .External.
Hao Chai (U of Iowa) Introduction to .Call interface 4 / 41
5. Introduction
Advantages of R
Straight forward syntax.
Easy to learn, to use, to track the results and to debug.
Over 3,000 packages available to carry out many kinds of statistical
analysis and produce professional graphics.
Vectorized language.
...
Disadvantage of R
Loops.
Hao Chai (U of Iowa) Introduction to .Call interface 5 / 41
6. Introduction
Advantages of R
Straight forward syntax.
Easy to learn, to use, to track the results and to debug.
Over 3,000 packages available to carry out many kinds of statistical
analysis and produce professional graphics.
Vectorized language.
...
Disadvantage of R
Loops.
Hao Chai (U of Iowa) Introduction to .Call interface 5 / 41
7. Introduction
Toy example
Our goal is to generate a variance-covariance matrix Σ = (σij ), where
a · b|i−j| , if i = j;
σij =
1, if i = j.
We have at least three methods:
A simple R function matgen R:
matgen_R = function(P, a, b)
{
Covmatrix = matrix(rep(1, P * P), nrow = P)
for (i in 1 : P)
for (j in 1 : P)
if (i != j)
Covmatrix[i, j] = exp(log(a) + log(b)
* abs(i - j))
Covmatrix
}
Hao Chai (U of Iowa) Introduction to .Call interface 6 / 41
8. Introduction
Toy example
An R function using matrix indexing matgen Rind:
matgen_Rind = function(P, a, b)
{
Covmatrix = matrix(rep(1, P * P), nrow = P)
for (i in 1 : (P - 1))
{Covmatrix[cbind((1 + i) : P, 1 : (P - i))] =
exp(log(a) + log(b) * abs(i))
Covmatrix[cbind(1 : (P - i), (1 + i) : P)] =
exp(log(a) + log(b) * abs(i))}
Covmatrix
}
Hao Chai (U of Iowa) Introduction to .Call interface 7 / 41
9. Introduction
An R function calling C routines matgen RC:
matgen_RC = function(P, a, b)
{
.Call("matrix_gen", as.integer(P), as.double(a),
as.double(b))
}
Also we can use R compiler to compile the first two pure R functions and
get matgen Rcmp and matgen Rindcmp.
Hao Chai (U of Iowa) Introduction to .Call interface 8 / 41
10. Introduction
Toy example
Result
> P = 1000
test elapsed user.self relative
5 matgen Rindcmp(P, 0.5, 0.9) 0.80 0.75 1.00
4 matgen Rind(P, 0.5, 0.9) 0.97 0.86 1.21
1 matgen RC(P, 0.5, 0.9) 1.04 1.01 1.30
2 matgen Rcmp(P, 0.5, 0.9) 19.98 19.51 24.98
3 matgen R(P, 0.5, 0.9) 65.44 64.45 81.80
Hao Chai (U of Iowa) Introduction to .Call interface 9 / 41
11. C part
Outline
1 Introduction
2 C part
.C interface
.Call interface
3 R part
4 Examples
5 Other
Hao Chai (U of Iowa) Introduction to .Call interface 10 / 41
12. C part
Header files
To enable the communication between R and C, the following header files
are needed in the C code.
#include <R.h>
#include <Rinternals.h> /% For .C or .Call %/
#include <Rdefines.h> /% For .External %/
#include <R_ext/Rdynload.h>
Hao Chai (U of Iowa) Introduction to .Call interface 11 / 41
13. C part .C interface
To use .C interface, main() function in C code needs to be replaced by
static void CFuncName(arg1, arg2, ...)
Arguments above have to be of pointer type. Therefore, we need to
coerce the scalar arguments to scalars in C.
C function can only return values to R through its arguments. In
other words, there are two kinds of arguments: arguments that pass
values from R to C and arguments that return values from C to R.
The C code using .C interface in the toy example is
Hao Chai (U of Iowa) Introduction to .Call interface 12 / 41
14. C part .C interface
.C interface in toy example
#include <R.h>
#include <Rinternals.h>
#include <R_ext/Rdynload.h>
#include <math.h>
static void matrix_gen(double *Rp, double *Ra, double *Rb,
double *Rmatrix)
{
R_len_t i, j, p = Rp[0];
double a = Ra[0], b = Rb[0];
for (i = 0; i < p; i++)
for (j = 0; j < p; j++)
if (i == j) Rmatrix[i * p + j] = 1;
else Rmatrix[i * p + j] = exp(log(a) + abs(i - j)
* log(b));
}
Hao Chai (U of Iowa) Introduction to .Call interface 13 / 41
15. C part .C interface
Mapping types between R and C
Table: Comparison of R and C data types.1
R storage mode C types
logical int *
integer int *
double double *
character char **
complex Rcomplex *
1
Cited from “Writing R Extensions”
Hao Chai (U of Iowa) Introduction to .Call interface 14 / 41
16. C part .Call interface
What can we expect from .Call?2
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
2
See Brian Caffo
Hao Chai (U of Iowa) Introduction to .Call interface 15 / 41
17. C part .Call interface
To use .Call interface, main() function in C code needs to be replaced by
SEXP CFuncName(SEXP arg1, SEXP arg2, ...)
SEXP is a structure in C standing for S expression.
The returned value from C will also be SEXP type.
If new SEXP objects are defined within the C function, use
PROTECT to protect them in the memory so that it will not be
cleaned by R as garbage.
Hao Chai (U of Iowa) Introduction to .Call interface 16 / 41
18. C part .Call interface
Basic structure of C functions
SEXP CFuncName(SEXP arg1, arg2, ...)
{
[arg1 = coerceVector(arg1, INTSXP)]
# Coerce the vector to the right type.
SEXP Robj, return_val; # Define new R objects.
PROTECT(return_val = allocMatrix(REALSXP, arg1, arg2))
# Protect return_val.
[body of function]
UNPROTECT(1)
return(return_val) # Return the values to R.
}
Hao Chai (U of Iowa) Introduction to .Call interface 17 / 41
19. C part .Call interface
Useful data types in Rinternals.h
3
Table: SEXPTYPE and R equivalent
SEXPTYPE R equivalent
REALSXP numeric with storage mode double
INTSXP integer
LGLSXP logical
STRSXP character
VECSXP list (generic vector)
DOTSXP a ‘...’ object
ENVSXP environment
3
Cited from “Writing R Extensions”
Hao Chai (U of Iowa) Introduction to .Call interface 18 / 41
20. C part .Call interface
Useful macros in Rinternals.h
There are plenty of useful functions defined in Rinternals.h. Useful
functions can be found in “Writing R Extensions” or “R Internals”.
Table: List of useful functions in Rinternals.h4
Name Usage Example
coerceVector Coerce R object to SEXPTYPE arg1=..(arg1,INTSXP)
allocVector Allocate memory for R vector Robj=..(STRSXP,2)
allocMatrix Allocate memory for R matrix Robj=..(STRSXP,2,2)
nrows Get the No. of rows of a matrix ..nrow(Rmatrix)
ncols Get the No. of cols of a matrix ..ncol(Rmatrix)
PROTECT Protect an R object See examples.
UNPROTECT UNPROTECT some R objects See examples.
4
.. represents the function name in the same row.
Hao Chai (U of Iowa) Introduction to .Call interface 19 / 41
21. C part .Call interface
Useful functions in Rinternals.h
Table: List of useful functions in Rinternals.h Cont.5
Name Usage Example
STRING ELT Returns the memo. add. of R string ..(Rstr, 0)
VECTOR ELT Returns the memo. add. of R list ..(Rlist, 1)
INTEGER Return the memo. add. of R int ..(Rint)
REAL Return the memo. add. of R real ..(Rdoub)
CHAR Convert a Rchar to characters ..(Rchar)
SET VECTOR ELT Assign value to an element of R list See example
5
.. represents the function name in the same row.
Hao Chai (U of Iowa) Introduction to .Call interface 20 / 41
22. C part .Call interface
Special Values
There are some constants for special values in R
R NaN
R PosInf
R NegInf
R NaReal
R NilValue
There are also some macros for error checking in C ISNA, ISNAN,
R FINITE, NA INTEGER, NA LOGICAL, NA STRING, NA REAL
Hao Chai (U of Iowa) Introduction to .Call interface 21 / 41
23. C part .Call interface
.Call interface in toy example
#include <R.h>
#include <Rinternals.h>
#include <R_ext/Rdynload.h>
#include "math.h"
SEXP matrix_gen(SEXP RP, SEXP Ra, SEXP Rb)
{
R_len_t i, j, p = INTEGER(RP)[0];
SEXP Rmatrix;
RP = coerceVector(RP, INTSXP);
Ra = coerceVector(Ra, REALSXP);
Rb = coerceVector(Rb, REALSXP);
PROTECT(Rmatrix = allocMatrix(REALSXP, p, p));
Hao Chai (U of Iowa) Introduction to .Call interface 22 / 41
24. C part .Call interface
.Call interface in toy example
double *mat, a = REAL(Ra)[0], b = REAL(Rb)[0];
mat = REAL(Rmatrix);
for (i = 0; i < p; i++)
for (j = 0; j < p; j++)
if (i == j) mat[i * p + j] = 1;
else mat[i * p + j] = exp(log(a) +
abs(i - j) * log(b));
UNPROTECT(1);
return(Rmatrix);
}
Hao Chai (U of Iowa) Introduction to .Call interface 23 / 41
25. R part
Outline
1 Introduction
2 C part
.C interface
.Call interface
3 R part
4 Examples
5 Other
Hao Chai (U of Iowa) Introduction to .Call interface 24 / 41
26. R part
Interfaces in R
To create a dynamic library, run the following code in the command line:
R CMD SHLIB CFileName.c
CFileName.dll or CFileName.so will be generated in the same directory.
Then load the dynamic library which is generated by C code using
> dyn.load("CFileName.so")
in Linux/MacOS, or
> dyn.load("CFileName.dll")
in Windows, or a universal solution
> dyn.load(paste("CFileName", .Platform$dynlib.ext,
+ sep = ""))
Hao Chai (U of Iowa) Introduction to .Call interface 25 / 41
27. R part
There are three interfaces in R to load the dynamic library generated by C.
1 .C(”CFuncName” arg1, arg2, ...)
,
2 .Call(”CFuncName” arg1, arg2, ...)
,
3 .External(”CFuncName”, arg1, arg2, ...)
There are some options when using .C, such as NAOK and
PACKAGE. For detailed information, refer to “Writing R Extensions”.
Hao Chai (U of Iowa) Introduction to .Call interface 26 / 41
28. Examples
Outline
1 Introduction
2 C part
.C interface
.Call interface
3 R part
4 Examples
5 Other
Hao Chai (U of Iowa) Introduction to .Call interface 27 / 41
29. Examples
Pass numeric values to C
func1 is a function with two arguments Rn and Rvec. It returns the largest
element of the first Rn elements of vector Rvec.
SEXP func1(SEXP Rvec, SEXP Rn)
{
Rvec = coerceVector(Rvec, REALSXP);
R_len_t i = 0, n = INTEGER(Rn)[0];
double *vec, max = REAL(Rvec)[0];
SEXP return_val;
PROTECT(return_val = allocVector(REALSXP, 1));
vec = REAL(Rvec);
for (i = 1; i < n; i++)
if (vec[i] >= max) max = vec[i];
REAL(return_val)[0] = max;
UNPROTECT(1);
return(return_val);
}
Hao Chai (U of Iowa) Introduction to .Call interface 28 / 41
30. Examples
Pass numeric values to C
In R, we do the following
a = c(7, 4, 8, 9, 2, 5)
n = 4
dyn.load("f:/presentation/intro2dotCall/illust.dll")
.Call("func1", as.double(a), as.integer(n))
Hao Chai (U of Iowa) Introduction to .Call interface 29 / 41
31. Examples
Pass strings, return a list
func2 is able to calculate the quadratic form or the linear product of a
matrix and a vector. It has three arguments: Rstr, Ry and RM. Ry is a
vector, RM is a matrix. If Rstr is ”quadratic”, then t(Ry) %*% RM %*%
Ry is returned. If Rstr is ”linear”, then RM %*% Ry is returned. If Rstr is
”both” then both of the above will be returned as an R list.
,
Hao Chai (U of Iowa) Introduction to .Call interface 30 / 41
32. Examples
Pass strings, return a list
SEXP func2(SEXP RM, SEXP Ry, SEXP Rstr)
{
Rstr = coerceVector(Rstr, STRSXP);
RM = coerceVector(RM, REALSXP);
Ry = coerceVector(Ry, REALSXP);
SEXP return_lst, vec, num;
double *M = REAL(RM), *y = REAL(Ry);
double result1 = 0, *result2;
R_len_t i, j, nr, nc, l;
const char *method;
method = CHAR(STRING_ELT(Rstr, 0));
nr = nrows(RM);
nc = ncols(RM);
l = length(Ry);
Hao Chai (U of Iowa) Introduction to .Call interface 31 / 41
33. Examples
if (((strcmp(method, "both") == 0) ||
(strcmp(method,"linear") == 0)) && (nc != l))
error("The matrix and the vector need to be conformable!");
if (((strcmp(method, "both") == 0) ||
(strcmp(method, "quadratic") == 0)) &&
((nc != l) || (nr != l)))
error("The matrix and the vector need to be conformable!");
if (strcmp(method, "both") == 0)
{
PROTECT(return_lst = allocVector(VECSXP, 2));
PROTECT(vec = allocVector(REALSXP, nr));
PROTECT(num = allocVector(REALSXP, 1));
result2 = REAL(vec);
result1 = REAL(num)[0];
}
else PROTECT(return_lst = allocVector(VECSXP, 1));
Hao Chai (U of Iowa) Introduction to .Call interface 32 / 41
34. Examples
if (strcmp(method, "linear") == 0)
{
PROTECT(vec = allocVector(REALSXP, nr));
result2 = REAL(vec);
}
if (strcmp(method, "quadratic") == 0)
{
PROTECT(num = allocVector(REALSXP, 1));
result1 = REAL(num)[0];
}
if ((strcmp(method, "quadratic") == 0) ||
(strcmp(method, "both") == 0))
for (i = 0; i < nr; i++)
for (j = 0; j < nc; j++)
result1 = result1 + M[i + j * nr] * y[i] * y[j];
Hao Chai (U of Iowa) Introduction to .Call interface 33 / 41
35. Examples
if ((strcmp(method, "linear") == 0) ||
(strcmp(method, "both") == 0))
for (i = 0; i < nr; i++)
{
result2[i] = 0;
for (j = 0; j < nc; j++)
result2[i] = result2[i] + M[i + j * nr] * y[j];
}
Hao Chai (U of Iowa) Introduction to .Call interface 34 / 41
36. Examples
if (strcmp(method, "quadratic") == 0)
SET_VECTOR_ELT(return_lst, 0, num);
if (strcmp(method, "linear") == 0)
SET_VECTOR_ELT(return_lst, 0, vec);
if (strcmp(method, "both") == 0)
{
SET_VECTOR_ELT(return_lst, 0, num);
SET_VECTOR_ELT(return_lst, 1, vec);
}
UNPROTECT(2);
if (strcmp(method, "both") == 0)
UNPROTECT(1);
return(return_lst);
}
Hao Chai (U of Iowa) Introduction to .Call interface 35 / 41
37. Examples
Pass strings, return a list
The R code to call the function func2 is
dyn.load("f:/presentation/intro2dotCall/illust.dll")
M <- matrix(c(1, 2, 3, 4, 5, 6, 7, 8, 9), nrow = 3)
y <- c(1, 0, -1)
.Call("func2", M, as.double(y), "both")
Hao Chai (U of Iowa) Introduction to .Call interface 36 / 41
38. Other
Outline
1 Introduction
2 C part
.C interface
.Call interface
3 R part
4 Examples
5 Other
Hao Chai (U of Iowa) Introduction to .Call interface 37 / 41
39. Other
Evaluating R expressions in C
It is also possible to evaluate R expressions in C code. The following
functions/macros are useful in this case. More details can be found in
“Writing R extensions” .
defineVar
findVar
findFun
install
Hao Chai (U of Iowa) Introduction to .Call interface 38 / 41
40. Other
Some misc.
The “Writing R Extensions” manual is the main source for this talk.
More functions and macros can be found in Rinternals.h, or
alternatively Rdefines.h. Choose one and stick to it.
Several times, when ran .Call in R, R crashed. Very likely, it was
caused by the difference between number of arguments in .Call and
number of arguments in the original C functions.
Related C and R files are available at Related files.
Hao Chai (U of Iowa) Introduction to .Call interface 39 / 41
41. Other
Refrences
Writing R Extensions
R Internals
Using .Call in R by Brian Caffo.
dot Call Interface by Gopi Goswami.
Rinternals.h
Hao Chai (U of Iowa) Introduction to .Call interface 40 / 41
42. Other
Thank you!
Hao Chai (U of Iowa) Introduction to .Call interface 41 / 41