R统计学入门基础问题
1. 如何生成100个高斯(正态)分布随机数
x <- rnorm(100, mean = 5, sd = 0.1)
x
# [1] 4.893534 5.046611 5.081097 4.979164 5.181700 5.038192 5.135376 5.173346 4.968877 4.986146
# [11] 4.946258 5.198199 5.055531 4.943075 5.073673 4.831518 5.020880 4.930038 5.069399 4.966239
# [21] 5.035919 4.748342 4.950412 5.098074 5.200755 5.016067 4.980694 5.092845 4.969212 5.166748
# [31] 5.063731 5.188161 5.067183 4.832255 4.948366 4.945234 5.281972 5.004589 5.052194 4.970655
# [41] 4.821950 5.172387 5.075971 4.881912 5.077742 4.959202 4.978079 5.071156 5.122046 5.099949
# [51] 5.056486 5.073163 4.986136 4.879002 5.035217 5.115133 5.170419 4.979108 4.999929 5.104167
# [61] 4.995740 5.136457 5.088393 5.068214 4.979342 4.862489 4.984418 4.851406 5.101475 5.009014
# [71] 4.955209 5.113826 4.993114 4.969778 5.174806 5.118025 4.940426 5.016818 5.008397 5.007662
# [81] 5.037553 4.841561 4.927540 4.792235 4.943234 5.025745 4.877301 5.006027 5.105440 4.816338
# [91] 5.078376 5.099721 4.976009 4.844325 4.920226 5.052165 5.042234 4.876854 5.053872 5.029314
mean(x)
# 5.015125
sd(x)
# 0.1027691
summary(x)
# Min. 1st Qu. Median Mean 3rd Qu. Max.
# 4.748 4.954 5.016 5.015 5.079 5.282
2. 如何清除内存所有变量
rm(list = ls(all = TRUE))
3. 如何更改小数显示数字位数
pi <- 3.1415926
# digits支持1-22个数字,默认为7
options(digits = 4)
pi
# 3.142
4. 如何通过R调用系统内程序
使用system()或shell.exec()函数启动程序
system(paste("C:/Program Files/Internet Explorer/iexplore.exe" ,"cran.r-project.org") , wait = FALSE)
system("notepad")
5. 如果本地升级R,不重装R包
其他目录安装R新版本,将就版本R程序的library目录下的R包复制至新的R library目录下,执行以下代码
update.packages()
6. 如何获取当前工作目录和设置工作目录
# 获取当前working directory
getwd()# 设置工作目录
setwd("目录路径")
7. 如何保存当前工作
# 工作目录生成.RData文件
save.image()# 保存R对象
pi <- 3.1415926
save(pi , file = "pi.data")
8. 如何获取本地安装的R包列表
.packages(all.available = TRUE)
# [1] "abind" "ade4"
# [3] "afex" "affy"
# [5] "affyio" "airway"
# [7] "ALL" "Amelia"
......
9. 如何查看函数的代码
summary# 查看类函数方法
methods(summary)
# [1] summary,ANY-method summary,CompressedIRangesList-method
# [3] summary,DBIObject-method summary,FilterResults-method
# [5] summary,FilterRules-method summary,Hits-method# 查看类函数lm方法代码
summary.lm
# function (object, correlation = FALSE, symbolic.cor = FALSE,
# ...)
# {
# z <- object
# p <- z$rank
# rdf <- z$df.residual
# if (p == 0) {
# r <- z$residuals
# n <- length(r)
# w <- z$weights
# if (is.null(w)) {
# rss <- sum(r^2)
# }
# else {
# rss <- sum(w * r^2)
# r <- sqrt(w) * r
# }
# resvar <- rss/rdf
# ans <- z[c("call", "terms", if (!is.null(z$weights)) "weights")]
# class(ans) <- "summary.lm"
# ans$aliased <- is.na(coef(object))
# ans$residuals <- r
# ans$df <- c(0L, n, length(ans$aliased))
# ans$coefficients <- matrix(NA_real_, 0L, 4L, dimnames = list(NULL,
# c("Estimate", "Std. Error", "t value", "Pr(>|t|)")))
# ans$sigma <- sqrt(resvar)
# ans$r.squared <- ans$adj.r.squared <- 0
# ans$cov.unscaled <- matrix(NA_real_, 0L, 0L)
# if (correlation)
# ans$correlation <- ans$cov.unscaled
# return(ans)
# }
# if (is.null(z$terms))
# stop("invalid 'lm' object: no 'terms' component")
# if (!inherits(object, "lm"))
# warning("calling summary.lm(<fake-lm-object>) ...")
# Qr <- qr.lm(object)
# n <- NROW(Qr$qr)
# if (is.na(z$df.residual) || n - p != z$df.residual)
# warning("residual degrees of freedom in object suggest this is not an \"lm\" fit")
# r <- z$residuals
# f <- z$fitted.values
# w <- z$weights
# if (is.null(w)) {
# mss <- if (attr(z$terms, "intercept"))
# sum((f - mean(f))^2)
# else sum(f^2)
# rss <- sum(r^2)
# }
# else {
# mss <- if (attr(z$terms, "intercept")) {
# m <- sum(w * f/sum(w))
# sum(w * (f - m)^2)
# }
# else sum(w * f^2)
# rss <- sum(w * r^2)
# r <- sqrt(w) * r
# }
# resvar <- rss/rdf
# if (is.finite(resvar) && resvar < (mean(f)^2 + var(c(f))) *
# 1e-30)
# warning("essentially perfect fit: summary may be unreliable")
# p1 <- 1L:p
# R <- chol2inv(Qr$qr[p1, p1, drop = FALSE])
# se <- sqrt(diag(R) * resvar)
# est <- z$coefficients[Qr$pivot[p1]]
# tval <- est/se
# ans <- z[c("call", "terms", if (!is.null(z$weights)) "weights")]
# ans$residuals <- r
# ans$coefficients <- cbind(Estimate = est, `Std. Error` = se,
# `t value` = tval, `Pr(>|t|)` = 2 * pt(abs(tval), rdf,
# lower.tail = FALSE))
# ans$aliased <- is.na(z$coefficients)
# ans$sigma <- sqrt(resvar)
# ans$df <- c(p, rdf, NCOL(Qr$qr))
# if (p != attr(z$terms, "intercept")) {
# df.int <- if (attr(z$terms, "intercept"))
# 1L
# else 0L
# ans$r.squared <- mss/(mss + rss)
# ans$adj.r.squared <- 1 - (1 - ans$r.squared) * ((n -
# df.int)/rdf)
# ans$fstatistic <- c(value = (mss/(p - df.int))/resvar,
# numdf = p - df.int, dendf = rdf)
# }
# else ans$r.squared <- ans$adj.r.squared <- 0
# ans$cov.unscaled <- R
# dimnames(ans$cov.unscaled) <- dimnames(ans$coefficients)[c(1,
# 1)]
# if (correlation) {
# ans$correlation <- (R * resvar)/outer(se, se)
# dimnames(ans$correlation) <- dimnames(ans$cov.unscaled)
# ans$symbolic.cor <- symbolic.cor
# }
# if (!is.null(z$na.action))
# ans$na.action <- z$na.action
# class(ans) <- "summary.lm"
# ans
# }
10. 如何在R中使用科学计数法
1e10 == 10000000000
# TRUE1.2e-4 == 0.00012
# TRUE
10. 如何在R中读取其他统计软件输入数据
使用 foreign 包,它可以读取 Minitab, S, SAS, SPSS, Stata, Systat, dBase 保存的数据。
foreign::read.spss()
foreign::read.S()
foreign::read.systat()
11. R如何读取excel数据
使用 foreign 包,它可以读取 Minitab, S, SAS, SPSS, Stata, Systat, dBase 保存的数据。
# 方法一,将excel数据保存为.csv文件
data <- read.csv("data.csv")# 方法二,使用xlsReadWrite R包
data <- read.xls("data.csv")# 方法三,使用RODBC包
library(RODBC)
file <− odbcConnectExcel ("rexceltest.xls")
data <− sqlFetch(file , "Sheet1")
close(file )
12. R如何快速保存输出结果至文本文件
使用sink()函数
data("mtcars")
sink(file = "mtcars.txt")
13. R如何将因子(factor)转换为数字
# f为因子对象
as.numeric(as.character(f))
# 或
as.numeric(levels(f))[as.integer(f)]
14. R如何可视化输入数据
打开可视化界面
data <- data.frame()
edit(data) # 或fix(data
15. R如何连接数据库读取数据
R支持基于SQL语言的关系数据库,RMySQL包提供MySQL数据库接口,RODBC包提供多种数据库接口(标准ODBC接口数据库)。经测试,Windows 平台上的 Microsoft SQL Server、Access、Oracle、MySQL、PostgreSQL,Linux 平台上的 MySQL、Oracle、PostgreSQL、SQLite 都有实际应用案例。
library(RODBC)
# 连接数据库
db <- odbcConnect("database_name", uid = "username", pwd = "password")
# 查询
stocks <- sqlQuery(db, "select * from quotes")
# 断开数据库连接
odbcClose(db)
16. R如何在一个变量中追加元素
x <- 1:10
x
# 1 2 3 4 5 6 7 8 9 10# 元素1后面追加元素0
append(x, 0, after = 1)
# 1 0 2 3 4 5 6 7 8 9 10# 元素5后面追加元素100
append(x, 100, after = 5)
# 1 2 3 4 5 100 6 7 8 9 10
17. R如何删除某行或某列数据
逗号在前删除行,逗号在后删除列,前面添加负号-
# 创建4x5矩阵
x <- data.frame(matrix(1:20, nrow = 4, byrow = 5))
x
# X1 X2 X3 X4 X5
#1 1 2 3 4 5
#2 6 7 8 9 10
#3 11 12 13 14 15
#4 16 17 18 19 20# 删除第1和第3行数据
x1 <- x[-c(1,3) ,]
x1
# X2 X4 X5
#1 2 4 5
#2 7 9 10
#3 12 14 15
#4 17 19 20# 删除第1和第3列数据
x2 <- x[, -c(1,3)]
x2
# X2 X4 X5
#1 2 4 5
#2 7 9 10
#3 12 14 15
# 17 19 20
18. R如何判断dataframe是否相同
# 创建dataframe
d1 <- data.frame(num = 1:8, lib = letters[1:8])
d1
# num lib
# 1 1 a
# 2 2 b
# 3 3 c
# 4 4 d
# 5 5 e
# 6 6 f
# 7 7 g
# 8 8 hd2 <- d1
# 将d2第3行第1列数值和第8行第2列数值赋值为2
d2[[3,1]] <- 2 -> d2[[8, 2]]
d2
# num lib
# 1 1 a
# 2 2 b
# 3 2 c
# 4 4 d
# 5 5 e
# 6 6 f
# 7 7 g
# 8 8 2any(d1==d2)
# TRUE, 至少1个值相同返回为TRUEall(d1==d2)
# FALSE, 全部值相同返回为TRUE# 获取2个dataframe不相同元素位置
which(d1 != d2, arr.ind = TRUE)
# row col
# [1,] 3 1
# [2,] 8 2
19. R如何去除重复元素
使用unique()或duplicated()函数
a1 <- c(1:20, 1:5, 3:6)
a1
# 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 1 2 3 4 5 3 4 5 6
unique(a1) 或 x <- x[!duplicated(x)]
# 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
20. R如何删除list中元素
lst <- list("l1" = list("a"=1, "b"=2), "l2" = list("a"=1, "b"=2))
lst
# $l1
# $l1$a
# [1] 1
#
# $l1$b
# [1] 2
#
#
# $l2
# $l2$a
# [1] 1
#
# $l2$b
# [1] 2# 删除l1中b元素
lst[["l1"]]["b"] <- NULL
# lst
# $l1
# $l1$a
# [1] 1
#
#
# $l2
# $l2$a
# [1] 1
#
# $l2$b
# [1] 2