7.-颜林林-R高级编程技巧及Rcpp的介绍

合集下载

c函数r语言

c函数r语言

c函数r语言摘要:一、C 函数和R 语言简介1.C 函数的作用和特点2.R 语言的定义和功能二、C 函数与R 语言的关联1.C 函数在R 语言中的使用场景2.R 语言调用C 函数的优势三、C 函数与R 语言的性能比较1.C 函数的执行速度2.R 语言的执行速度3.C 函数与R 语言性能比较的结果四、C 函数与R 语言在实际应用中的选择1.根据需求选择C 函数或R 语言2.结合实际案例分析C 函数与R 语言的使用正文:C 函数和R 语言是两种在不同场景下发挥作用的编程语言。

C 函数主要是用于编写底层的系统程序和应用程序,它具有执行速度快、效率高等特点。

而R 语言则是一种用于数据处理、统计分析和可视化的编程语言,它的功能强大且易于使用。

C 函数与R 语言之间存在紧密的联系。

在实际应用中,C 函数可以作为R 语言的一个扩展库,通过加载这些库,R 语言用户可以在不离开R 语言环境的情况下使用C 函数。

这为R 语言用户带来了许多便利,比如提高了执行速度、增强了程序的兼容性等。

在性能方面,C 函数相较于R 语言具有更快的执行速度。

由于C 函数是编译型语言,其执行速度接近于C 或C++,而R 语言是解释型语言,其执行速度相对较慢。

因此,在处理大数据或对执行速度有较高要求的场景中,使用C 函数会比使用R 语言更加合适。

在实际应用中,C 函数与R 语言的选择需要根据具体需求来决定。

对于数据处理、统计分析和可视化等任务,R 语言是一个很好的选择,因为它具有丰富的统计方法和可视化工具。

而在需要提高执行速度或处理大量数据的场景下,可以考虑使用C 函数或C++等编译型语言。

总之,C 函数与R 语言在不同的场景下发挥着各自的作用。

C 函数为R 语言提供了更快的执行速度和更高的性能,而R 语言则以其易用性和丰富的功能为数据处理和统计分析提供了便利。

快速入门R编程

快速入门R编程

快速入门R编程在大数据时代的到来下,数据成为了企业决策的重要依据。

而R语言作为一种强大的数据分析工具,近年来逐渐流行起来。

本文将带您快速入门R编程,帮助您快速上手并掌握这一强大工具。

1. R语言简介R语言是一种开源的、适用于统计分析与绘图的编程语言。

由于其灵活性、丰富的数据分析库和庞大的开发者社区,R语言成为数据科学家和统计学家的首选工具。

可以应用于数据清洗、数据可视化、机器学习等各个领域。

2. 安装R语言要开始使用R语言,首先需要在计算机上安装R软件。

可以在官方网站上下载相应的安装包,并按照提示完成安装过程。

3. RStudio介绍RStudio是一个集成开发环境(IDE),专门为R语言设计。

它提供了强大的代码编辑、调试和工作空间管理功能,使得编程更加便捷。

安装完R语言后,可以下载并安装RStudio。

4. R基础语法R语言的语法与其他编程语言相比较容易上手。

以下是一些常用的基础语法示例:- 定义变量:```x <- 10```- 执行表达式:```x + 5```- 条件语句:```if (x > 5) {print("x大于5")} else {print("x小于等于5") }```- 循环语句:```for (i in 1:5) {print(i)}```- 函数定义:```my_function <- function(a, b) {return(a + b)}```- 函数调用:```result <- my_function(3, 4)print(result)```5. 数据处理R语言提供了丰富的数据处理库,可以对数据进行清洗、转换、整理等操作。

以下是一些常用的处理函数示例:- 数据读取:```data <- read.csv("data.csv")```- 数据清洗:```clean_data <- na.omit(data)```- 数据过滤:filtered_data <- subset(data, column > 10)```- 数据整合:```merged_data <- merge(data1, data2, by = "id")```- 数据排序:```sorted_data <- arrange(data, column)```- 数据汇总:```summary_data <- summarize(data, avg = mean(column), total = sum(column))```6. 数据可视化R语言最大的优势之一就是数据可视化能力。

R软件总结

R软件总结
2
对于向量的加(+)、减(-)、乘(*)、除(/)和乘方(^),其含义是对每一个元素进行运算。例如:
> x <- c(-1, 0, 2); y <- c(3, 8, 2)
> v <- 2*x + y + 1; v
[1] 2 9 7
> x * y
[1] -3 0 4
> x / y
[1] -0.3333333 0.0000000 1.0000000
其四个参数中最多有三个参数,不能四个参数同时存在
3
y<-rep(x,3)即:将x重复三次赋给y
2.2.3
逻辑运算有< , <= , > , >= , == , !=
两个逻辑变量的与(&),或(|),非(!)
例如:x <- 1:7
> l <- x > 3;l
[1] FALSE FALSE FALSE TRUE TRUE TRUE TRUE
> x
[1] 2 3 4
2
例:
> v <- 10:20
> v[c(1,3,5,9)]
[1] 10 12 14 18
> v[c(1,2,3,2,1)]
[1] 10 11 12 11 10
> v[1:5]
[1] 10 11 12 13 14
> c("a","b","c")[rep(c(2,1,3), times=3)]
7、图形中的子图par(mfrow = c(i,j)),画i行j列个子图,先行后列
8、数据框的中变量的水平很重要levels()

Rcpp包使用指南说明书

Rcpp包使用指南说明书

Writing a package that uses Rcpp Dirk Eddelbuettel a and Romain François ba ;b https://romain.rbind.io/This version was compiled on July3,2023This document provides a short overview of how to use Rcpp(Ed-delbuettel et al.,2023a;Eddelbuettel and François,2011;Eddelbuettel, 2013)when writing an R package.It shows how usage of the function Rcpp.package.skeleton which creates a complete and self-sufficient ex-ample package using Rcpp.All components of the directory tree created by Rcpp.package.skeleton are discussed in detail.This document thereby complements the Writing R Extensions manual(R Core Team,2021)which is the authoritative source on how to extend R in general.Rcpp|package|R|C++1.IntroductionRcpp(Eddelbuettel et al.,2023a;Eddelbuettel and François,2011; Eddelbuettel,2013)is an extension package for R which offers an easy-to-use yet featureful interface between C++and R.However,it is somewhat different from a traditional R package because its key component is a C++library.A client package that wants to make use of the Rcpp features must link against the library provided by Rcpp.It should be noted that R has only limited support for C(++)-level dependencies between packages(R Core Team,2021).The LinkingTo declaration in the package DESCRIPTIONfile allows the client package to retrieve the headers of the target package(here Rcpp),but support for linking against a library is not provided by R and has to be added manually.This document follows the steps of the Rcpp.package.skeleton function to illustrate a recommended way of using Rcpp from a client package.We illustrate this using a simple C++function which will be called by an R function.We strongly encourage the reader to become familiar with the material in the Writing R Extensions manual(R Core Team,2021), as well as with other documents on R package creation such as Leisch(2008).Given a basic understanding of how to create R package,the present document aims to provide the additional information on how to use Rcpp in such add-on packages.ing Rcpp.package.skeleton2.1.Overview.Rcpp provides a function Rcpp.package.skeleton,modeled after the base R func-tion package.skeleton,which facilitates creation of a skeleton package using Rcpp.Rcpp.package.skeleton has a number of arguments documented on its help page(and similar to those of package.skeleton).The main argument is thefirst one which provides the name of the package one aims to create by invoking the function.An illustration of a call using an argument mypackage is providedbelow.Using Rcpp.package.skeleton is by far the simplest approach as it fulfills two roles.It creates the complete set offiles needed for a package,and it also includes the different components needed for using Rcpp that we discuss in the following sections.2.2.C++code.If the attributes argument is set to TRUE1,the following C++file is included in the src/directory:Thefile defines the simple rcpp_hello_world function that uses a few Rcpp classes and returns a List.This function is preceded by the Rcpp::export attribute to automatically handle argument conversion because R has to be taught how to e.g.handle the List class.Rcpp.package.skeleton then invokes compileAttributes on the package,which generates the RcppExports.cppfile(where we indented thefirst two lines for the more compact display here): 1Setting attributes to TRUE is the default.This document does not cover the behavior of Rcpp.package.skeleton when attributes is set to FALSE as we try to encourage package de-veloppers to use attributes.https:///package=Rcpp Rcpp Vignette|July3,2023|1–4Thisfile defines a function with the appropriate calling con-vention,suitable for.Call.It needs to be regenerated each time functions exposed by attributes are modified.This is the task of the compileAttributes function.A discussion on attributes is be-yond the scope of this document and more information is available in the attributes vignette(Allaire et al.,2023).2.3.R code.The compileAttributes also generates R code that uses the C++function.This is also a generatedfile so it should not be modified manually, rather regenerated as needed by compileAttributes.2.4.DESCRIPTION.The skeleton generates an appropriate DESCRIPTIONfile,using both Imports:and LinkingTo for Rcpp:Rcpp.package.skeleton adds the three last lines to the DESCRIPTIONfile generated by package.skeleton.The Imports declaration indicates R-level dependency between the client package and Rcpp;code from the latter is being imported into the package described here.The LinkingTo declaration indi-cates that the client package needs to use headerfiles exposed by Rcpp.2.5.Now optional:Makevars and Makevars.win.This behaviour changed with Rcpp release0.11.0.Thesefiles used to be manda-tory,now they are merely optional.We will describe the old settingfirst as it was in use for a few years.The new standard,however,is much easier and is described below.2.6.Releases up until0.10.6.Unfortunately,the LinkingTo decla-ration in itself was not enough to link to the user C++library of Rcpp.Until more explicit support for libraries is added to R,ones needes to manually add the Rcpp library to the PKG_LIBS variable in the Makevars and Makevars.winfiles.(This has now changed with release0.11.0;see below).Rcpp provides the unexported function Rcpp:::LdFlags()to ease theprocess:The Makevars.win is the equivalent,targetingwindows.2.7.Releases since0.11.0.As of release0.11.0,this is no longer needed as client packages obtain the required code from Rcpp via explicit function registration.The user does not have to do anything.This means that PKG_LIBS can now be empty—unless some client libraries are needed.For example,RcppCNPy needs com-pression support and hence uses PKG_LIBS=-lz.Similarly,whena third-party library is required,it can and should be set here.SPACE.The Rcpp.package.skeleton function also cre-ates afile NAMESPACE.Thisfile serves three purposes.First,it ensure that the dynamic library contained in the package we are creating via Rcpp.package.skeleton will be loaded and thereby made avail-able to the newly created R package.Second,it declares which functions should be globally visible from the namespace of this package.As a reasonable default,we export all functions.Third,it instructs R to import a symbol from Rcpp.This sets up the import of all registered function and,together with the2|https:///package=Rcpp Eddelbuettel and FrançoisImports:statement in DESCRIPTION,provides what is needed for client packages to access Rcpp functionality.2.9.Helpfiles.Also created is a directory man containing two help files.One is for the package itself,the other for the(single)R function being provided and exported.The Writing R Extensions manual(R Core Team,2021)provides the complete documentation on how to create suitable content for helpfiles.2.10.mypackage-package.Rd.The helpfile mypackage-package.Rd can be used to describe the new package(and we once again indented somelines):2.11.rcpp_hello_world.Rd.The helpfile rcpp_hello_world.Rd serves as documentation for the ex-ample Ring modulesThis document does not cover the use of the module argument of Rcpp.package.skeleton.It is covered in the modules vignette (Eddelbuettel and François,2023).4.Further examplesThe canonical example of a package that uses Rcpp is the RcppEx-amples(Eddelbuettel and François,2019)package.RcppExam-ples contains various examples of using Rcpp.Hence,the RcppEx-amples package is provided as a template for employing Rcpp in packages.Other CRAN packages using the Rcpp package are RcppAr-madillo(Eddelbuettel et al.,2023b),and minqa(Bates et al., 2014).Several other packages follow older(but still supported and appropriate)instructions.They can serve examples on how to get data to and from C++routines,but should not be considered templates for how to connect to Rcpp.The full list of packages using Rcpp can be found at the CRAN page of Rcpp.5.Other compilersLess experienced R users on the Windows platform frequently ask about using Rcpp with the Visual Studio toolchain.That is simply not possible as R is built with the gcc compiler.Different compilers have different linking conventions.These conventions are particularly hairy when it comes to using C++.In short,it is not possible to simply drop sources(or headerfiles)from Rcpp into a C++project built with Visual Studio,and this note makes no attempt at claiming otherwise.Rcpp is fully usable on Windows provided the standard Win-dows toolchain for R is used.See the Writing R Extensions manual (R Core Team,2021)for details.6.SummaryThis document described how to use the Rcpp package for R and C++integration when writing an R extension package.The use of the Rcpp.package.skeleton was shown in detail,and references to further examples were provided.ReferencesAllaire JJ,Eddelbuettel D,François R(2023).Rcpp Attributes.Vignette included in R package Rcpp,URL https:///package=Rcpp.Eddelbuettel and François Rcpp Vignette|July3,2023|3Bates D,Mullen KM,Nash JC,Varadhan R(2014).minqa:Derivative-freeoptimization algorithms by quadratic approximation.R package version1.2.4,URL https:///package=minqa.Eddelbuettel D(2013).Seamless R and C++Integration with e R!Springer,New Y ork.ISBN978-1-4614-6867-7.Eddelbuettel D,François R(2011).“Rcpp:Seamless R and C++Integration.”Journal of Statistical Software,40(8),1–18.doi:10.18637/jss.v040.i08.URL https:///10.18637/jss.v040.i08.Eddelbuettel D,François R(2019).RcppExamples:Examples using Rcpp tointerface R and C++.R package version0.1.9,URL https://CRAN.R-Project.org/package=RcppExamples.Eddelbuettel D,François R(2023).Exposing C++functions and classes withRcpp modules.Vignette included in R package Rcpp,URL https://CRAN./package=Rcpp.Eddelbuettel D,François R,Allaire J,Ushey K,Kou Q,Russel N,Chambers J,Bates D(2023a).Rcpp:Seamless R and C++Integration.R package version1.0.11,URL https:///package=Rcpp.Eddelbuettel D,François R,Bates D,Ni B,Sanderson C(2023b).RcppArmadillo:Rcpp integration for Armadillo templated linear algebra library.R packageversion0.12.4.1.0,URL https:///package=RcppArmadillo.Leisch F(2008).“T utorial on Creating R Packages.”In P Brito(ed.),COMPSTA T2008–Proceedings in Computational Statistics.Physica Verlag,Heidelberg.URL https:///doc/contrib/Leisch-CreatingPackages.pdf.R Core Team(2021).Writing R extensions.R Foundation for Statistical Comput-ing,Vienna,Austria.URL https:///doc/manuals/R-exts.html.4|https:///package=Rcpp Eddelbuettel and François。

R语言编程技巧和实践方法

R语言编程技巧和实践方法

R语言编程技巧和实践方法R语言是一种功能强大的编程语言,被广泛应用于数据分析和统计建模领域。

掌握一些R语言的编程技巧和实践方法,可以提高数据分析的效率和准确性。

本文将介绍一些常用的R语言编程技巧和实践方法。

一、向量化操作在R语言中,向量化操作是一种高效的数据处理方式。

通过将操作应用于整个向量,可以避免使用循环,提高代码的执行速度。

例如,计算两个向量的和可以直接使用“+”运算符,而不需要使用循环遍历每个元素。

二、函数的使用R语言提供了丰富的函数库,可以满足各种数据分析的需求。

熟练掌握常用函数的使用方法,可以简化代码的编写。

例如,使用apply函数可以对矩阵的每一行或每一列进行操作,而不需要使用循环。

三、数据清洗与处理在进行数据分析时,数据的质量和准确性至关重要。

R语言提供了一些函数和技巧,可以帮助我们进行数据清洗和处理。

例如,使用na.omit函数可以删除包含缺失值的观测,使用duplicated函数可以检测和删除重复的观测。

四、数据可视化数据可视化是数据分析的重要环节。

R语言提供了多种数据可视化的函数和包,可以帮助我们将数据转化为图形,更直观地展示数据的分布和趋势。

例如,使用ggplot2包可以绘制出漂亮而丰富的图形,使用plotly包可以创建交互式图表。

五、代码的优化在进行大规模数据分析时,代码的执行效率往往成为一个关键问题。

R语言提供了一些优化技巧,可以提高代码的执行速度。

例如,使用矩阵代替数据框可以减少内存的占用,使用并行计算可以加快代码的运行速度。

六、调试和错误处理在编写代码时,经常会遇到错误和异常情况。

R语言提供了一些调试和错误处理的工具,可以帮助我们定位和解决问题。

例如,使用debug函数可以设置断点,查看代码的执行过程,使用tryCatch函数可以捕获和处理错误。

七、代码的复用和模块化为了提高代码的可维护性和可复用性,我们可以将一些常用的代码片段封装成函数或模块。

R语言提供了函数和包的机制,可以方便地实现代码的复用和模块化。

学习使用R编程语言进行数据分析

学习使用R编程语言进行数据分析

学习使用R编程语言进行数据分析近年来,数据分析在许多领域中变得越来越重要。

无论是市场营销、金融、医疗保健还是社交媒体,数据分析可以帮助我们从庞大且复杂的数据集中提取有关趋势和模式的信息。

在这方面,R编程语言已经成为了许多数据科学家和分析师的首选工具。

本文将介绍学习使用R编程语言进行数据分析的一些基本概念和技巧。

首先,让我们了解一下R编程语言的基本概念。

R是一种免费、开源的编程语言和环境,专门用于数据分析和统计建模。

它提供了丰富的库和工具,可以用于数据清洗、数据转换、数据可视化和机器学习等任务。

与其他编程语言相比,R的语法相对简单和直观,使得入门变得更加容易。

接下来,我们将讨论几个常用的R库,这些库可以帮助我们进行数据分析。

其中之一是“dplyr”。

它是一个功能强大的数据处理库,提供了一些简单直观的函数,用于对数据集进行常见的操作,例如过滤、排序和分组。

另一个重要的库是“ggplot2”,它是一个用于数据可视化的库。

通过使用“ggplot2”,我们可以轻松创建各种类型的图表和图形,以更好地理解数据之间的关系。

此外,还有一些其他流行的R库,如“caret”和“tidyverse”,也可以提供各种数据分析和建模任务的支持。

学习使用R编程语言进行数据分析的一个关键方面是数据的读取和清洗。

通常,我们需要将数据从外部源导入R环境中,并对其进行一些预处理。

例如,我们可以使用“read.csv”函数读取一个CSV文件,并使用“head”函数查看文件前几行的内容。

一旦数据加载到R环境中,我们可以使用“dplyr”库进行数据清洗。

例如,我们可以使用“filter”函数根据特定的条件筛选数据行,或者使用“mutate”函数将新的变量添加到数据集中。

通过学习这些基本操作,我们可以确保数据的准确性和一致性。

接下来,我们将学习如何使用R进行数据可视化。

数据可视化是数据分析过程中的重要环节,它可以帮助我们更好地理解数据之间的关系和趋势。

初学者如何学习编写R语言的入门教程

初学者如何学习编写R语言的入门教程

初学者如何学习编写R语言的入门教程R语言是一种广泛应用于数据分析和统计建模的高级编程语言。

对于初学者来说,学习R语言可能会感到有些困惑和挑战。

然而,通过有序的学习和实践,初学者可以逐渐掌握R语言的技巧和概念。

本文将介绍一些学习R语言的基本步骤和方法,帮助初学者进入这个有趣且强大的编程世界。

一、了解R语言的基本概念在开始学习R语言之前,初学者需要对R语言的基本概念有一定的了解。

R语言是一种面向数据分析和统计建模的编程语言,具有易学易用的特点。

初学者可以通过阅读相关的书籍、教程或者观看在线视频来了解R语言的基本概念,例如变量、函数、数据类型、数据结构等。

二、选择合适的学习资源学习R语言需要掌握一定的理论知识和实践经验。

初学者可以选择一些优质的学习资源来帮助他们系统地学习R语言。

这些学习资源可以包括在线课程、学习社区、编程书籍、编程博客等等。

通过这些学习资源,初学者可以获取R语言的知识和技巧,并有机会与其他学习者进行交流和分享经验。

三、实践编写R语言代码学习R语言最重要的一点是实践,通过编写R语言代码来巩固所学的知识和技能。

初学者可以选择一些简单的练习题或者项目来进行实践,例如数据清洗、数据可视化、统计分析等。

在实践中,初学者可以逐渐熟悉R语言的语法和常用函数,并学会解决实际问题的能力。

四、参与开源项目和社区R语言有一个活跃的开源社区,初学者可以通过参与开源项目和社区来拓展自己的知识和技能。

参与开源项目可以让初学者接触到一些实践中的问题和挑战,并有机会与更有经验的R语言开发者进行合作和交流。

此外,初学者还可以利用社区资源,例如论坛、邮件列表等,向其他R语言学习者寻求帮助和建议。

五、持续学习和提升学习R语言是一个不断学习和提升的过程。

初学者应该保持对R语言的兴趣和热情,并不断学习新的知识和技能。

可以在日常工作或者学习中尝试使用R语言解决问题,参加相关的培训或者会议,阅读最新的研究成果等等。

通过不断地学习和实践,初学者可以逐渐提升自己在R语言上的能力,并成为一个熟练的R语言开发者。

r语言的基础语法及常用命令

r语言的基础语法及常用命令

r语言的基础语法及常用命令R语言是一种用于数据分析和统计建模的编程语言,它具有丰富的基础语法和常用命令。

本文将介绍R语言的基础语法和常用命令,帮助读者快速入门和理解R语言的使用。

1. 变量和数据类型在R语言中,可以通过使用赋值符号“<-”或“=”来创建变量,并且不需要事先声明变量的类型。

R语言支持多种数据类型,包括数值型、字符型、逻辑型、因子型等。

例如,可以使用以下代码创建一个数值型变量x,并赋值为10:```Rx <- 10```2. 数据结构R语言中常用的数据结构包括向量、矩阵、数组、数据框和列表。

向量是最基本的数据结构,可以存储多个相同类型的元素。

矩阵是二维的数据结构,可以存储多个相同类型的元素。

数组是多维的数据结构,可以存储多个相同类型的元素。

数据框是类似于Excel表格的数据结构,可以存储多个不同类型的变量。

列表是一种包含不同类型元素的数据结构。

3. 控制结构R语言中常用的控制结构包括条件语句(if-else语句)和循环语句(for循环、while循环)。

条件语句用于根据条件执行不同的代码块。

例如,以下代码展示了一个简单的if-else语句:```Rx <- 10if (x > 5) {print("x大于5")} else {print("x小于等于5")}```循环语句用于重复执行一段代码块。

例如,以下代码展示了一个简单的for循环:```Rfor (i in 1:5) {print(i)}```4. 函数R语言中的函数是一段具有特定功能的代码块,可以重复使用。

R语言提供了许多内置函数,还可以自定义函数。

例如,以下代码展示了一个自定义函数,用于计算两个数的和:```Rsum <- function(a, b) {return(a + b)}result <- sum(3, 5)print(result) # 输出8```5. 数据读写R语言中可以通过各种方式读取和写入数据。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

LGPL 65
... ...
R语言的广泛运用
高校、科研机构、企事业单位…… 金融、通讯、医药、生物、环境……
COS论坛
创办于2006年5月19日 截至2011年5月28日: 整个论坛:
主题:16,000+;回复:109,000+
“S-Plus & R语言”版:
主题:4,000+;回复:27,000+
举例:求DNA互补链
DNA由A、C、T、G组成 DNA两条链方向相反 成对碱基,A与T配对,C与G配对 已知其中一条为“ACTGAAGTGC” 求另一条序列
举例:求DNA互补链
# 方法一:循环 方法一: revcom1 <- function(DNA) { result <- '' for (i in nchar(DNA):1) { n <- substr(DNA, i, i) if (n == 'A') result <'') if (n == 'T') result <'') if (n == 'C') result <'') if (n == 'G') result <'') } result }
R是一门解释型语言
> system.time(replicate(10000, b <- sin(a))) user system elapsed 0.44 0.10 0.59 > b <- vector() > system.time(replicate(10000, for (i in seq_along(a)) {b[i] <- sin(a[i])})) user system elapsed 6.15 0.02 6.44
函数tapply
> (d <- data.frame( name = c("Alice", "Bob", "Kate", "Jim"), age = c(20, 25, 28, 24), gender = c("Female", "Male", "Female", "Male"))) name age gender 1 Alice 20 Female 2 Bob 25 Male 3 Kate 28 Female 4 Jim 24 Male > c(class(d), class(d$age), class(d$gender)) [1] "data.frame" "numeric" "factor" > tapply(d$age, d$gender, mean) Female Male 24.0 24.5
学习R的一个捷径:
在COS上回帖!
论坛中一些常见关于R的问题
如何画XX图? 如何实现XX功能? 安装时遇到XX问题如何解决? 如何提高R程序的运行效率? …… 《153分钟学会R》
正题:如何让R飞起来
R高级编程技巧 向量运算 软件包的使用 Rcpp的介绍 结合不同语言的优势 拓展R的运用范围
向量运算“是一种习惯”
函数sapply和vapply
> (v <- c("Min."=0, "1st Qu."=0, "Median"=0, "3rd Qu."=0, "Max."=0)) Min. 1st Qu. Median 3rd Qu. Max. 0 0 0 0 0 > vapply(X, fivenum, v) [,1] [,2] [,3] Min. 1.0 1.0 1 1st Qu. 1.5 1.5 2 Median 2.0 2.5 3 3rd Qu. 2.5 3.5 4 Max. 3.0 4.0 5
apply系列函数
apply(), sapply(), lapply(), tapply(), ...
其他各种函数
sum(), mean(), cumsum(), combn(), ...
R语言元素类型
整数(integer) 1:10 实数(numeric, double) c(1.1, 3.14, 10) 复数(complex) 字符(character) 逻辑(logical) 原始数据(raw) 因子(factor) c(1+i, 3-2i) c("a", "b", "COS") c(TRUE, FALSE) as.raw(48) as.factor(letter[1:3])
把苦力活交给底层,尽量避免使用循环!
如何掌握好向量运算
R语言基本数据类型
vector, matrix, array, data.frame, list, ...
元素的提取方法
a[1:3], a[-2], a[a>3], a[c("x","y")], ...
数据类型之间的互相转换
as.matrix(), as.vector(), as.character(), ...
函数sapply和vapply
> (X <- sapply(3:5, seq)) [[1]] [1] 1 2 3 [[2]] [1] 1 2 3 4 [[3]] [1] 1 2 3 4 5 > sapply(X, fivenum) [,1] [,2] [,3] [1,] 1.0 1.0 1 [2,] 1.5 1.5 2 [3,] 2.0 2.5 3 [4,] 2.5 3.5 4 [5,] 3.0 4.0 5
函数rapply
> (X <- list(list(a=pi, b=list(c=1:1)), d="a test")) [[1]] [[1]]$a [1] 3.141593 [[1]]$b [[1]]$b$c [1] 1 $d [1] "a test" > rapply(X, function(x) x) a b.c "3.14159265358979" "1" d "a test"
R高级编程技巧及Rcpp的介绍
颜林林
北京大学生物信息中心
2011年5月28日
R语言的特点
F
REE:开源、免费、自由、灵活
> a <- available.packages(contrib.url( "/mirrors/CRAN", "source")) > nrow(a)
Hale Waihona Puke > tr T G C A "A" "C" "G" "T"
方法比较
> library(rbenchmark) > benchmark( revcom1(DNA), revcom2(DNA), revcom3(DNA), columns = c("test", "replications", "elapsed", "relative"), order = "relative", replications = 1000) test replications elapsed relative 3 revcom3(DNA) 2 revcom2(DNA) 1 revcom1(DNA) 1000 1000 1000 0.163 1.000000 0.597 3.662577 0.624 3.828221
从C到C++
字符串、数组等类型 内存的管理 模板和泛型编程 STL (Standard Template Library)
举例:求DNA互补链
# 方法三:names() 方法三: revcom3 <- function(DNA) { tr <- c('A','C','G','T') names(tr) <- rev(tr) paste(tr[rev(strsplit(DNA, '')[[1]])], collapse = '') }
R的灵活性
R是什么语言写成的?
C/C++、Fortran、R
R的外部扩展
Writing R Extensions
R与各种语言
R + bash / Rscript RDCOM rJava rpy, rpy2 Embeded Rserve、R API、Rcpp
R 与 C++
R(解释型语言) 无需编译 不需要其它文件 弱类型语言 灵活性好 运行速度较慢 其他特性 向量运算 大量统计和绘图函数 C++(编译型语言) 需要事先编译 需要头文件和库文件 强类型语言 灵活性相对较差 运行速度快 其他特性 面向对象 模板与泛型编程
循环的思维方式: for (p in 参加R大会的人) { 发资料给p; 发胸牌给p; 发……给p; }
> a <- 1:100 > a * 2 > sin(a)
生活中的思维方式: 发资料、胸牌等 给参加R大会的人
能用更少的话说清楚,就别罗嗦!
R是一门解释型语言
> a <- 1:100 > # 向量运算 > b <- sin(a) > # 循环 > b <- vector() > for (i in seq_along(a)) { b[i] <- sin(a[i]) }
相关文档
最新文档