• R 常用基本函数


    R 常用的数字、矩阵和数列的处理函数

    数值篇

    mean() #均值
    colMeans() #对列求均值
    sum() #求和
    max() #最大值
    min() #最小值
    prod() #连乘
    var() #方差
    sd() #标准差
    seq() #产生序列  seq(1,100,by=2) 产生1到100,公差为2的数列;seq(1,100,length=25)产生1到100,数字个数为25的数列.
    letters[m:n] #依次输出第m到n个英文小写字母
    LETTERS[m:n] #依次输出第m到n个英文大写字母
    which() #返回符合条件的的坐标   which.max() 返回最大值坐标,which.min()返回最小值坐标
    rev() #反序输出数列
    sort() #对象量进行排序
    intersect() #交集
    union()  #并集
    setdiff() #找不同
    setequal() #判断相同
    

    矩阵篇

    is.matrix() #判断是否是矩阵  矩阵也是数组的特殊形式,可以看做二维的数组
    matrix(a,nrow=m,ncol=n) #新建m行n列矩阵,默认按列排序,按行加参数byrow = T
    t() #矩阵转置
    diag() #返回矩阵对角线(输入为矩阵时)或产生阶数为数值的单位矩阵
    solve()  #矩阵求逆(输入矩阵时); solve(a,c) 求 a·x = c, a矩阵乘以x等于c矩阵,求x
    eigen() #求矩阵的特征值
    

    向量

    is.vector() #判断是否为向量
    

    数组

    is.array() #判断是否为数组
    mode()  # 判断
    

    数据框

    data.frame()  #矩阵形式,但列可以不同数据类型
    plot() # 绘出图形
    

    排列组合

    choose(n,k) # 从n个中选出k个的可能组合个数
    combn(n,k) # 从n个中选出k个的组合结果
    factorial(k) # k的阶乘

    未整理

    !!! reference: https://statisticsglobe.com/r-functions-list/

    abline – Add straight lines to plot.
    abs – Compute the absolute value of a numeric data object.
    aggregate – Compute summary statistics of subgroups of a data set.
    all – Check whether all values of a logical vector are TRUE.
    all_equal [dplyr] – Compare two data frames.
    anti_join [dplyr] – Anti join two data frames.
    any – Check whether any values of a logical vector are TRUE.
    apply – Apply function by rows or columns of a data frame.
    apropos – Return character vector with names of objects that contain the input.
    arrange [dplyr] – Order data frames and tibbles.
    attach – Give access to variables of a data.frame.
    attr – Return or set a specific attribute of a data object.
    attributes – Return or set all attributes of a data object.
    as.Date – Convert character strings to Date class.
    as.double – Convert integer to double class.
    as.factor – Convert a data object to the class factor.
    as.name – Convert character string to name class object.
    as.numeric – Convert a data object to the class numeric.
    as.tbl [dplyr] – Convert data.frame to tibble.
    axis – Create user-defined axis ticks.
    barplot – Create a barplot.
    beep [beepr] – Play sound at the end of an R script.
    between [dplyr] – Test whether a numeric value falls into a specified range.
    bind_cols [dplyr] – Bind columns and vectors.
    bind_rows [dplyr] – Bind rows of data sets.
    boxplot – Create a boxplot.
    break – Break for-loop in R.
    call – Create objects of the class call.
    case_when [dplyr] – Distinguish between cases based on logical conditions.
    casefold – Translate character to lower or upper case.
    cases [memisc] – Distinguish between cases based on logical conditions.
    cat – Return character string in readable format.
    cbind – Combine vectors, matrices and/or data frames by column.
    ceiling – Round numeric up to the next higher integer.
    charmatch – Return position of first match between two data objects.
    chartr – Translate characters of string to lower and/or upper case.
    coalesce [dplyr] – Replace missing values.
    colMeans – Compute the mean of each column of a numeric data frame, matrix or array.
    colMedians [robustbase] – Compute the median of each column of a numeric matrix.
    colnames – Retrieve or set the column names of a data frame or matrix.
    colSums – Compute the sum of each column of a numeric data frame, matrix or array.
    combn [combinat] – Generate all possible combinations of vector object.
    combine [dplyr] – Combine values.
    complete.cases – Return a logical vector that indicates which cases have no missing values.
    cumall [dplyr] – Apply cumulative version of all Function.
    cumany [dplyr] – Apply cumulative version of any Function.
    cume_dist [dplyr] – Rank a vector.
    cummean [dplyr] – Apply cumulative version of mean Function.
    cumsum – Calculate the cumulative sum of the elements of a numeric vector.
    cut – Convert numeric values into factorial ranges.
    dbeta – Return corresponding value of beta density.
    dbern – Return corresponding value of bernoulli PDF.
    dbinom – Return corresponding value of binomial density.
    dcauchy – Return corresponding value of cauchy density.
    dchisq – Return corresponding value of chi-square PDF.
    dense_rank [dplyr] – Rank a vector.
    density – Draw Kernel Density Plot.
    deparse – Convert an expression to the character class.
    detach – Remove the attachment of a data.frame or unload a package.
    dexp – Return corresponding value of exponential density.
    df – Return corresponding value of F PDF.
    dgamma – Return corresponding value of gamma density.
    dgeom – Return corresponding value of geometric PDF.
    dhyper – Return corresponding value of hypergeometric PDF.
    diff – Compute difference between pairs of consecutive elements of a vector.
    difftime – Calculate the time difference of two date or time objects.
    dim – Return the dimension (e.g. the number of columns and rows) of a matrix, array or data frame.
    dir – Return a character vector of file and/or folder names within a directory.
    dist – Compute distance matrices.
    distCosine [geosphere] – Calculate the Law of Cosines great circle distance.
    distHaversine [geosphere] – Calculate the Haversine great circle distance.
    distinct [dplyr] – Retain only unique rows of data set.
    distMeeus [geosphere] – Calculate the Meeus great circle distance.
    distRhumb [geosphere] – Calculate a distance along a rhumb line.
    distVincentySphere [geosphere] – Calculate the Vincenty Sphere great circle distance.
    distVincentyEllipsoid [geosphere] – Calculate the Vincenty Ellipsoid great circle distance.
    dlnorm – Return corresponding value of log normal PDF.
    dlogis – Return corresponding value of logistic PDF.
    dnbinom – Return corresponding value of negative binomial density.
    dnorm – Create standard normal distribution.
    do.call – Execute function by its name and a list of corresponding arguments.
    download.file – Download file from internet.
    dpois – Return value of poisson density.
    droplevels – Remove unused levels of a factor.
    dsignrank – Return corresponding PDF value of wilcoxon signedank statistic.
    dt – Return corresponding value of Student t PDF.
    dtukey – Return corresponding value of studentized range PDF.
    dunif – Return corresponding value of uniform PDF.
    dweibull – Return corresponding value of weibull density.
    dwilcox – Return corresponding PDF value of wilcoxon rank sum statistic.
    ecdf – Compute the Empirical Cumulative Distribution Function (ECDF).
    eval – Evaluate an expression and return the result.
    exists – Check whether an object is defined in the R environment.
    expression – Create an R object of the expression class.
    filter [dplyr] – Subset rows by logical condition.
    find – Return location where objects of a given name can be found.
    first [dplyr] – Extract first value from vector.
    floor – Round numeric down to the next lower integer.
    format – Encode data objects into common formats.
    full_join [dplyr] – Full join two data frames.
    gather [tidyr] – Reshape data frame from wide to long format in R.
    geom_bar – Create a barplot.
    geom_boxplot [ggplot2] – Create a boxplot.
    geom_histogram [ggplot2] – Draw a histogram.
    geom_line [ggplot2] – Draw a line graph.
    geometric.mean [psych] – Compute the geometric mean.
    get – Search and call a data object.
    get0 – Call an existing data object or return an alternative value.
    getwd – Return filepath of the current working directory.
    ggpairs [GGally] – Return a matrix of plots based on a given data set.
    gregexpr – Search for match of certain character pattern.
    grep – Search for match of certain character pattern and return indices.
    grepl – Search for match of certain character pattern and return logical.
    gsub – Replace all matches in character string.
    harmonic.mean [psych] – Compute the harmonic mean.
    heatmap – Create heatmap in Base R.
    hist – Create histogram.
    if_else [dplyr] – Conditionally select an element.
    ifelse – Select elements conditionally.
    inner_join [dplyr] – Inner join two data frames.
    integrate – Integrate a user-defined function.
    IQR – Compute the Interquartile Range.
    is.double – Test whether a data object has the double class.
    is.na – Return a logical vector or matrix indicating which elements are missing.
    is.name – Test whether a data object has the class name.
    is.nan – Return a logical vector or matrix indicating which elements are not a number.
    is.null – Return a logical value indicating whether a data object is of the data class NULL.
    is.tbl [dplyr] – Check if data object is a tibble.
    is.unsorted – Check whether an input is unsorted.
    jitter – Add noise to a numeric vector.
    julian – Return the number of days between two date objects.
    lag [dplyr] – Lag a vector.
    lapply – Apply function to all list elements.
    last [dplyr] – Extract last value from vector.
    layout – Specify complex plot arrangements.
    lead [dplyr] – Lead a vector.
    left_join [dplyr] – Left join two data frames.
    length – Return the length of data objects such as vectors or lists.
    libPath – Get or set directory path of installed packages.
    list.dirs – Obtain list of directories.
    list.files – List files with specific extension in working directory.
    load – Load RData workspace file into R.
    log – Compute logarithms of numeric values.
    log2 – Compute logarithms of numeric values with base of 2.
    log10 – Compute logarithms of numeric values with base of 10.
    lowess – Compute the lowess smoother.
    mapply – Apply function to multiple data groups.
    match – Return position of first match between two data objects.
    max – Compute the maximum value of a vector or column.
    mad – Compute the median absolute deviation.
    mean – Compute the arithmetic mean.
    median – Compute the median.
    melt [reshape2] – Reshape data frame from wide to long format in R.
    merge – Merge data frames.
    message – Generate diagnostic message.
    mget – Search and call several data objects.
    min – Compute the minimum value of a vector or column.
    min_rank [dplyr] – Rank a vector.
    Mode [DescTools] – Compute the mode.
    months – Return the corresponding month of a date.
    mutate [dplyr] – Add new variable to data set.
    n.readLines [reader] – Skip ahead in a file and read text lines.
    na.omit – Remove incomplete cases of a data object.
    na_if [dplyr] – Replace NA values.
    names – Return or set the names of a data object.
    nchar – Return the number of elements (e.g. letters) of a character object.
    ncol – Return the number of columns of a matrix or data frame.
    near [dplyr] – Compare numeric vectors.
    next – Skip certain parts of for-loop in R.
    nrow – Return the number of rows of a matrix or data frame.
    nth [dplyr] – Extract certain values from vector.
    ntile [dplyr] – Rank a vector.
    object.size – Report the space allocated for an object.
    optim – Apply general-purpose optimization.
    optimize – Perform one dimensional optimization.
    order – Return position of each input element in ascending or descending order.
    outer – Apply a function to two arrays.
    packageVersion – Find out the currently loaded version of an R package.
    pairs – Return a plot matrix consisting of scatterplots for each variable-combination of a data frame.
    par – Set or Query graphical parameters.
    parse – Convert a character to the expression class.
    paste – Concatenate inputs to string.
    paste0 – Concatenate inputs to string with given separator.
    pbern – Return corresponding value of bernoulli CDF.
    pbeta – Return corresponding value of beta cumulative distribution function.
    pbinom – Return corresponding value of binomial cumulative distribution function.
    pcauchy – Return corresponding value of cauchy cumulative distribution function.
    pchisq – Return corresponding value of chi-square CDF.
    percent [formattable] – Format number as percentage.
    percent [scales] – Format number as percentage.
    percent_rank [dplyr] – Rank a vector.
    permn [combinat] – Generate all possible permutatins of vector object.
    pexp – Return corresponding value of exponential cumulative distribution function.
    pf – Return corresponding value of F CDF.
    pgamma – Return corresponding value of gamma cumulative distribution function.
    pgeom – Return corresponding value of geometric CDF.
    phyper – Return corresponding value of hypergeometric CDF.
    pivot_longer [tidyr] – Reshape data from wide to long format.
    pivot_wider [tidyr] – Reshape data from long to wide format.
    plnorm – Return corresponding value of log normal CDF.
    plogis – Return corresponding value of logistic CDF.
    plot – Draw a scatterplot or density plot.
    pmatch – Return position of first match between two data objects.
    pmax – Return the parallel maxima of two or more vectors.
    pmin – Return the parallel minima of two or more vectors.
    pnbinom – Return corresponding value of negative binomial cumulative distribution function.
    pnorm – Return value of distribution function.
    polygon – Draw a polygon to a plot.
    ppois – Return value of poisson cumulative distribution function.
    pretty – Compute a sequence of equally spaced round values.
    print – Return data object to the R (or RStudio) console.
    psignrank – Return corresponding CDF value of wilcoxon signedank statistic.
    pt – Return corresponding value of Student t CDF.
    ptukey – Return corresponding value of studentized range CDF.
    pull [dplyr] – Extract columns of data frame or tibble.
    punif – Return corresponding value of uniform CDF.
    pweibull – Return corresponding value of weibull CDF.
    pwilcox – Return corresponding CDF value of wilcoxon rank sum statistic.
    qbern – Return corresponding value of bernoulli quantile function.
    qbeta – Return corresponding value of beta quantile function.
    qbinom – Return corresponding value of binomial quantile function.
    qcauchy – Return corresponding value of cauchy quantile function.
    qchisq – Return corresponding value of chi-square quantile function.
    qexp – Return corresponding value of exponential quantile function.
    qf – Return corresponding value of F quantile function.
    qgamma – Return corresponding value of gamma quantile function.
    qgeom – Return corresponding value of geometric quantile function.
    qhyper – Return corresponding value of hypergeometric quantile function.
    qlnorm – Return corresponding value of log normal quantile function.
    qlogis – Return corresponding value of logistic quantile function.
    qnbinom – Return corresponding value of negative binomial quantile function.
    qnorm – Return value of quantile function.
    qpois – Return value of poisson quantile function.
    qqnorm – Create a normal QQplot.
    qsignrank – Return corresponding quantile function value of wilcoxon signedank statistic.
    qt – Return corresponding value of Student t quantile function.
    qtukey – Return corresponding value of studentized range quantile function.
    quantile – Compute sample quantiles.
    quarters – Return the corresponding quarter of a date.
    qunif – Return corresponding value of uniform quantile function.
    qweibull – Return corresponding value of weibull quantile function.
    qwilcox – Return corresponding quantile function value of wilcoxon rank sum statistic.
    R.Version – Get current R version.
    rank – Return ranking position of input.
    rbern – Return bernoulli distributed random number.
    rbeta – Draw random number from beta density.
    rbind – Combine vectors, matrices and/or data frames by row.
    rbind.fill [plyr] – Row-bind matrices or data frames with different columns.
    rbinom – Draw random number from binomial density.
    rcauchy – Draw random number from cauchy density.
    rchisq – Return chi-square distributed random number.
    read_excel [readxl Package] – Read Excel File in R.
    read.xlsx [xlsx Package] – Read Excel File in R.
    read.xlsx [openxlsx Package] – Read Excel File in R.
    readline – Interactively read a line from the terminal.
    readLines – Read text lines from an input file.
    readRDS – Load RData workspace file into R.
    recode [dplyr] – Replace certain values of a vector.
    recode_factor [dplyr] – Replace certain values of a factor vector.
    regexpr – Search for match of certain character pattern.
    regexec – Search for match of certain character pattern.
    remove – Clear specific data object from R workspace.
    rename [dplyr] – Rename variables of data frame or tibble.
    rm – Clear specific data object from R workspace.
    rep – Replicate elements of vectors and lists.
    replace – Exchanges values in data object.
    return – Return output of user-defined R function.
    rev – Return a reversed version of vectors or other data objects.
    rexp – Draw random number from exponential density.
    rf – Return F distributed random number.
    rgamma – Draw random number from gamma density.
    rgeom – Return geometrically distributed random number.
    rhyper – Return hypergeometrically distributed random number.
    right_join [dplyr] – Right join two data frames.
    rlnorm – Return log normally distributed random number.
    rlogis – Return logistically distributed random number.
    rnbinom – Draw random number from negative binomial density.
    rnorm – Draw normally distributed random number.
    rollmean [zoo] – Calculate moving average.
    rollmax [zoo] – Calculate moving maximum.
    rollmedian [zoo] – Calculate moving median.
    rollsum [zoo] – Calculate moving sum.
    round – Round numeric to specified number of decimal places.
    row_number [dplyr] – Rank a vector.
    row.names – Get or set row names of data frame or matrix.
    rowMeans – Compute the mean of each row of a numeric data frame, matrix or array.
    rowMedians [robustbase] – Compute the median of each row of a numeric matrix.
    rowSums – Compute the sum of each row of a numeric data frame, matrix or array.
    rpois – Draw random value of poisson density.
    rsignrank – Return random number according to wilcoxon signedank statistic.
    rt – Return Student t distributed random number.
    rtukey – Return studentized range distributed random number.
    runif – Return uniformly distributed random number.
    rweibull – Draw random value of weibull density.
    rwilcox – Return random number according to wilcoxon rank sum statistic.
    sample – Take a random sample or permutation of a data object.
    sample_frac [dplyr] – Take a sample of a certain fraction of a data set.
    sample_n [dplyr] – Take a sample of N cases of a data set.
    sapply – Apply function to all list elements and convert output to vector.
    save – Save R data objects as RData workspace file.
    save.image – Save global R environment as RData workspace file.
    saveRDS – Save single R data object as RData workspace file.
    scale – Standardize data.
    scale_colour_brewer [ggplot2] – Change color palette in ggplot2 plot.
    scale_fill_brewer [ggplot2] – Change palette of filling colors in ggplot2 plot.
    scan – Read data into vector or list from file or R console.
    sd – Compute standard deviation.
    segments – Draw a line segment between two pairs of points.
    select [dplyr] – Select variables of data frame or tibble.
    semi_join [dplyr] – Semi join two data frames.
    seq – Generate sequence of numeric values.
    set.seed – Set a random seed.
    setdiff – Identify which elements of a data object X are not existent in a data object Y.
    setNames [stats] – Set names of a data object and return the object.
    setnames [data.table] – Change names of a data.frame or data.table by reference.
    setwd – Specify new working directory.
    shapiro.test – Perform Shapiro-Wilk normality test.
    sign – Return the signs of numeric elements.
    signif – Round numeric to specified number of digits.
    sink – Export R output to external file.
    slice [dplyr] – Extract certain rows of data set.
    solve – Solve system of equations.
    sort – Return input in ascending or descending order.
    sort.int – Return input in ascending or descending order.
    sort.list – Return position of each element of a single input.
    split – Divide data into groups.
    sprintf – Return character containing a formatted combination of input values.
    sqrt – Compute the square root of a numeric data object.
    stat_qq_line [ggplot2] – Add theoretical line to QQplot.
    std.error [plotrix] – Compute standard error in R.
    stop – Generate error message and stop executing the current R code.
    str_c [stringr] – Combine several inputs into a single character vector.
    str_count [stringr] – Count number of matches in a character string.
    str_detect [stringr] – Detect presence or absence of pattern in character string.
    str_dup [stringr] – Duplicate and concatenate strings within a character vector.
    str_ends [stringr] – Detect the presence or absence of a pattern at the end of a character string.
    str_extract [stringr] – Extract matching patterns from character string .
    str_flatten [stringr] – Flatten a character string.
    str_length [stringr] – Return the length of a string.
    str_locate [stringr] – Locate the first position of patterns in a character string.
    str_locate_all [stringr] – Locate the position of patterns in a character string.
    str_match [stringr] – Extract first matched groups from a string.
    str_match_all [stringr] – Extract matched groups from a string.
    str_order [stringr] – Order a vector of character strings.
    str_remove [stringr] – Remove first matched patterns in a character string.
    str_remove_all [stringr] – Remove all matched patterns in a character string.
    str_replace [stringr] – Replace first matched patterns in character strings.
    str_replace_all [stringr] – Replace all matched patterns in character strings.
    str_replace_na [stringr] – Replace NA values in a character string.
    str_sort [stringr] – Sort a vector of character strings.
    str_split [stringr] – Split up a string into pieces.
    str_split_fixed [stringr] – Split up a string into a fixed amount of pieces.
    str_starts [stringr] – Detect the presence or absence of a pattern at the beginning of a character string.
    str_sub [stringr] – Extract or replace substring from character string.
    str_subset [stringr] – Extract character strings matching a pattern.
    str_trim [stringr] – Trim whitespace from a character string.
    str_trunc [stringr] – Truncate character strings.
    str_which [stringr] – Identify positions in a character string matching a pattern.
    str_wrap [stringr] – Wrap a character string into nicely formatted paragraphs.
    strftime – Convert time objects to characters.
    strptime – Convert characters to time objects.
    strsplit – Split elements of a character string.
    structure – Set additional attributes of a data object.
    sub – Replace first match in character string.
    substr – Extract or replace a substring in a character vector.
    substring – Extract or replace a substring in a character vector.
    sum – Compute the sum of a numeric input vector.
    summary – Compute summary statistics of data and model objects.
    sweep – Apply an operation (e.g. + or -) to a matrix by row or column.
    switch – Run a specific code block and return its result.
    t – Transpose data frame.
    tapply – Apply function to multiple data groups.
    text – Draw text elements to plots.
    tolower – Translate character to lower case.
    top_frac [dplyr] – Extract certain fraction at the top of data.
    top_n [dplyr] – Extract first n rows of data.
    toupper – Translate character to upper case.
    transform – Modify data frames easily.
    transmute [dplyr] – Create new variable based on data set.
    trimws – Trim Leading and Trailing Whitespace.
    trunc – Cut off decimal places of a numeric input.
    tryCatch – Check expressions for error and warning messages.
    type.convert – Convert data object to appropriate class.
    union – Return values that appear in at least one of two data objects.
    unique – Remove duplicates from data objects.
    unit [grid] – Create data object with the class unit.
    unlist – Convert a list to a single vector.
    unsplit – Reverse output of split function.
    vapply – Apply function to all list elements and convert output to vector.
    var – Compute sample variance.
    warning – Generate warning message.
    weekdays – Return the corresponding weekday of a date.
    weighted.mean – Compute the weighted arithmetic mean.
    weightedMean [matrixStats] – Compute the weighted arithmetic mean.
    which – Return indices of certain values based on logical condition.
    with – Evaluates expression in environment constructed based on data frame.
    within – Evaluates expression in environment and modify data frame.
    write – Write data to files.
    write.xlsx [xlsx] – Export data frame from R to Excel workbook.
    wt.mean [SDMTools] – Compute the weighted arithmetic mean.
    xtfrm – Produce numeric vector which sorts in same order as input.
    xyplot [lattice] – Create scatterplot.

  • 相关阅读:
    【BZOJ 2844】: albus就是要第一个出场
    BZOJ 2631: tree
    BZOJ1798: [Ahoi2009]Seq 维护序列seq
    Link-Cut Tree指针模板
    bzoj 4916: 神犇和蒟蒻 (杜教筛+莫比乌斯反演)
    【BZOJ 3561】 DZY Loves Math VI
    linux 安装php7.2 以及配置laravel环境(public目录下)
    composer 配置 切换中国镜像
    phpstorm composer 提示php 版本过低的问题调整
    如何在阿里云的虚机 部署laravel项目
  • 原文地址:https://www.cnblogs.com/drliu/p/12939715.html
Copyright © 2020-2023  润新知