【工具提升】R語言溫故知新(1)

R basic

數(shù)學運算

## 四則運算
5 + (2.3 -1.125) * 3.2/1.1 + 1.23E3
## [1] 1238.418
#1.23E = 1.23 * 10^3

2^10
## [1] 1024
## 平方根
sqrt(6.25)
## [1] 2.5
## 指數(shù)
exp(1)
## [1] 2.718282
## 對數(shù)
log10(1000)
## [1] 3
## 取整(四舍五入)
round(1.1234,2)
## [1] 1.12
## 向下取整
floor(1.1234)
## [1] 1
## 向上取整
ceiling(1.1234)
## [1] 2
## 三角函數(shù) pi表示圓周率楚午。sin正弦, cos余弦, tan正切, 自變量以弧度為單位逸嘀。 pi/6是30度鞋诗。
pi
## [1] 3.141593
sin(pi/6)
## [1] 0.5
cos(pi/6)
## [1] 0.8660254
sqrt(3)/2
## [1] 0.8660254
tan(pi/6)
## [1] 0.5773503
## 反三角函數(shù) asin反正弦, acos反余弦, atan反正切爬泥, 結(jié)果以弧度為單位猜惋。
pi/6
## [1] 0.5235988
asin(0.5)
## [1] 0.5235988
acos(sqrt(3)/2)
## [1] 0.5235988
atan(sqrt(3)/3)
## [1] 0.5235988

分布函數(shù)和分位數(shù)函數(shù)

## dnorm(x)表示標準正態(tài)分布密度 . pnorm(x)表示標準正態(tài)分布函數(shù)折汞。 qnorm(y)表示標準正態(tài)分布分位數(shù)函數(shù) 咒劲。求自由度為10的t檢驗的雙側(cè)臨界值会放。 其中qt(y,df)表示自由度為df的t分布的分位數(shù)函數(shù)饲齐。
dnorm(1.98)
## [1] 0.05618314
pnorm(1.98)
## [1] 0.9761482
qnorm(0.975)
## [1] 1.959964
qt(1-0.05/2,10)
## [1] 2.228139

數(shù)據(jù)輸出

## 需要用print()函數(shù)顯示一個表達式的結(jié)果
print(sin(pi/2))
## [1] 1
## 用cat()函數(shù)顯示多項內(nèi)容, 包括數(shù)值和文本鸦概, 文本包在兩個單撇號或兩個雙撇號中
## cat()函數(shù)最后一項一般是"\n", 表示換行箩张。 忽略此項將不換行。

cat("sin(pi/2)=", sin(pi/2),"\n")
## sin(pi/2)= 1

函數(shù)運行記錄

sink("tmpres_20200819.txt", split=TRUE)
print(sin(pi/6))
## [1] 0.5
print(cos(pi/6))
## [1] 0.8660254
cat("t(10)的雙側(cè)0.05分位數(shù)(臨界值)=", qt(1 - 0.05/2, 10), "\n")
## t(10)的雙側(cè)0.05分位數(shù)(臨界值)= 2.228139
sink()

向量計算與變量賦值

## 向量生成
x1 <- 1:10
x2 <- c(3,4,5,6,7)

x3<- x2 *2
x3 - x2
## [1] 3 4 5 6 7
## R的許多函數(shù)都可以用向量作為自變量窗市, 結(jié)果是自變量的每個元素各自的函數(shù)值先慷。
sqrt(x3)
## [1] 2.449490 2.828427 3.162278 3.464102 3.741657
## 某人存入10000元1年期定期存款,年利率3%, 約定到期自動轉(zhuǎn)存(包括利息)咨察。
10000 * (1 + 3/100)^20
## [1] 18061.11

R 繪圖

## 用curve()函數(shù)制作函數(shù)的曲線圖论熙, curve()函數(shù)第二、第三自變量是繪圖區(qū)間:
curve(x^5, -2, 2)
image.png
## 類似的用sin函數(shù)曲線圖用如下程序制作摄狱,用abline()函數(shù)添加參考線
curve(sin(x),0,2*pi)
abline(h=0)
image.png
## 條形圖
barplot(c("男"=10,"女"=8),main="男女人數(shù)")
image.png
## 散點圖
plot(1:10,pnorm(1:10))
image.png
demo("graphics")
## 
## 
##  demo(graphics)
##  ---- ~~~~~~~~
## 
## > #  Copyright (C) 1997-2009 The R Core Team
## > 
## > require(datasets)
## 
## > require(grDevices); require(graphics)
## 
## > ## Here is some code which illustrates some of the differences between
## > ## R and S graphics capabilities.  Note that colors are generally specified
## > ## by a character string name (taken from the X11 rgb.txt file) and that line
## > ## textures are given similarly.  The parameter "bg" sets the background
## > ## parameter for the plot and there is also an "fg" parameter which sets
## > ## the foreground color.
## > 
## > 
## > x <- stats::rnorm(50)
## 
## > opar <- par(bg = "white")
## 
## > plot(x, ann = FALSE, type = "n")
image.png
## 
## > abline(h = 0, col = gray(.90))
## 
## > lines(x, col = "green4", lty = "dotted")
## 
## > points(x, bg = "limegreen", pch = 21)
## 
## > title(main = "Simple Use of Color In a Plot",
## +       xlab = "Just a Whisper of a Label",
## +       col.main = "blue", col.lab = gray(.8),
## +       cex.main = 1.2, cex.lab = 1.0, font.main = 4, font.lab = 3)
## 
## > ## A little color wheel.    This code just plots equally spaced hues in
## > ## a pie chart.    If you have a cheap SVGA monitor (like me) you will
## > ## probably find that numerically equispaced does not mean visually
## > ## equispaced.  On my display at home, these colors tend to cluster at
## > ## the RGB primaries.  On the other hand on the SGI Indy at work the
## > ## effect is near perfect.
## > 
## > par(bg = "gray")
## 
## > pie(rep(1,24), col = rainbow(24), radius = 0.9)
image.png
## 
## > title(main = "A Sample Color Wheel", cex.main = 1.4, font.main = 3)
## 
## > title(xlab = "(Use this as a test of monitor linearity)",
## +       cex.lab = 0.8, font.lab = 3)
## 
## > ## We have already confessed to having these.  This is just showing off X11
## > ## color names (and the example (from the postscript manual) is pretty "cute".
## > 
## > pie.sales <- c(0.12, 0.3, 0.26, 0.16, 0.04, 0.12)
## 
## > names(pie.sales) <- c("Blueberry", "Cherry",
## +              "Apple", "Boston Cream", "Other", "Vanilla Cream")
## 
## > pie(pie.sales,
## +     col = c("purple","violetred1","green3","cornsilk","cyan","white"))
image.png
## 
## > title(main = "January Pie Sales", cex.main = 1.8, font.main = 1)
## 
## > title(xlab = "(Don't try this at home kids)", cex.lab = 0.8, font.lab = 3)
## 
## > ## Boxplots:  I couldn't resist the capability for filling the "box".
## > ## The use of color seems like a useful addition, it focuses attention
## > ## on the central bulk of the data.
## > 
## > par(bg="cornsilk")
## 
## > n <- 10
## 
## > g <- gl(n, 100, n*100)
## 
## > x <- rnorm(n*100) + sqrt(as.numeric(g))
## 
## > boxplot(split(x,g), col="lavender", notch=TRUE)
image.png
## 
## > title(main="Notched Boxplots", xlab="Group", font.main=4, font.lab=1)
## 
## > ## An example showing how to fill between curves.
## > 
## > par(bg="white")
## 
## > n <- 100
## 
## > x <- c(0,cumsum(rnorm(n)))
## 
## > y <- c(0,cumsum(rnorm(n)))
## 
## > xx <- c(0:n, n:0)
## 
## > yy <- c(x, rev(y))
## 
## > plot(xx, yy, type="n", xlab="Time", ylab="Distance")
image.png
## 
## > polygon(xx, yy, col="gray")
## 
## > title("Distance Between Brownian Motions")
## 
## > ## Colored plot margins, axis labels and titles.    You do need to be
## > ## careful with these kinds of effects.    It's easy to go completely
## > ## over the top and you can end up with your lunch all over the keyboard.
## > ## On the other hand, my market research clients love it.
## > 
## > x <- c(0.00, 0.40, 0.86, 0.85, 0.69, 0.48, 0.54, 1.09, 1.11, 1.73, 2.05, 2.02)
## 
## > par(bg="lightgray")
## 
## > plot(x, type="n", axes=FALSE, ann=FALSE)
image.png
## 
## > usr <- par("usr")
## 
## > rect(usr[1], usr[3], usr[2], usr[4], col="cornsilk", border="black")
## 
## > lines(x, col="blue")
## 
## > points(x, pch=21, bg="lightcyan", cex=1.25)
## 
## > axis(2, col.axis="blue", las=1)
## 
## > axis(1, at=1:12, lab=month.abb, col.axis="blue")
## 
## > box()
## 
## > title(main= "The Level of Interest in R", font.main=4, col.main="red")
## 
## > title(xlab= "1996", col.lab="red")
## 
## > ## A filled histogram, showing how to change the font used for the
## > ## main title without changing the other annotation.
## > 
## > par(bg="cornsilk")
## 
## > x <- rnorm(1000)
## 
## > hist(x, xlim=range(-4, 4, x), col="lavender", main="")
image.png
## 
## > title(main="1000 Normal Random Variates", font.main=3)
## 
## > ## A scatterplot matrix
## > ## The good old Iris data (yet again)
## > 
## > pairs(iris[1:4], main="Edgar Anderson's Iris Data", font.main=4, pch=19)
image.png
## 
## > pairs(iris[1:4], main="Edgar Anderson's Iris Data", pch=21,
## +       bg = c("red", "green3", "blue")[unclass(iris$Species)])
image.png
## 
## > ## Contour plotting
## > ## This produces a topographic map of one of Auckland's many volcanic "peaks".
## > 
## > x <- 10*1:nrow(volcano)
## 
## > y <- 10*1:ncol(volcano)
## 
## > lev <- pretty(range(volcano), 10)
## 
## > par(bg = "lightcyan")
## 
## > pin <- par("pin")
## 
## > xdelta <- diff(range(x))
## 
## > ydelta <- diff(range(y))
## 
## > xscale <- pin[1]/xdelta
## 
## > yscale <- pin[2]/ydelta
## 
## > scale <- min(xscale, yscale)
## 
## > xadd <- 0.5*(pin[1]/scale - xdelta)
## 
## > yadd <- 0.5*(pin[2]/scale - ydelta)
## 
## > plot(numeric(0), numeric(0),
## +      xlim = range(x)+c(-1,1)*xadd, ylim = range(y)+c(-1,1)*yadd,
## +      type = "n", ann = FALSE)
image.png
## 
## > usr <- par("usr")
## 
## > rect(usr[1], usr[3], usr[2], usr[4], col="green3")
## 
## > contour(x, y, volcano, levels = lev, col="yellow", lty="solid", add=TRUE)
## 
## > box()
## 
## > title("A Topographic Map of Maunga Whau", font= 4)
## 
## > title(xlab = "Meters North", ylab = "Meters West", font= 3)
## 
## > mtext("10 Meter Contour Spacing", side=3, line=0.35, outer=FALSE,
## +       at = mean(par("usr")[1:2]), cex=0.7, font=3)
## 
## > ## Conditioning plots
## > 
## > par(bg="cornsilk")
## 
## > coplot(lat ~ long | depth, data = quakes, pch = 21, bg = "green3")
image.png
## 
## > par(opar)
demo("image")
## 
## 
##  demo(image)
##  ---- ~~~~~
## 
## > #  Copyright (C) 1997-2009 The R Core Team
## > 
## > require(datasets)
## 
## > require(grDevices); require(graphics)
## 
## > x <- 10*(1:nrow(volcano)); x.at <- seq(100, 800, by=100)
## 
## > y <- 10*(1:ncol(volcano)); y.at <- seq(100, 600, by=100)
## 
## >                    # Using Terrain Colors
## > 
## > image(x, y, volcano, col=terrain.colors(100),axes=FALSE)
image.png
## 
## > contour(x, y, volcano, levels=seq(90, 200, by=5), add=TRUE, col="brown")
## 
## > axis(1, at=x.at)
## 
## > axis(2, at=y.at)
## 
## > box()
## 
## > title(main="Maunga Whau Volcano", sub = "col=terrain.colors(100)", font.main=4)
## 
## >                    # Using Heat Colors
## > 
## > image(x, y, volcano, col=heat.colors(100), axes=FALSE)
image.png
## 
## > contour(x, y, volcano, levels=seq(90, 200, by=5), add=TRUE, col="brown")
## 
## > axis(1, at=x.at)
## 
## > axis(2, at=y.at)
## 
## > box()
## 
## > title(main="Maunga Whau Volcano", sub = "col=heat.colors(100)", font.main=4)
## 
## >                    # Using Gray Scale
## > 
## > image(x, y, volcano, col=gray(100:200/200), axes=FALSE)
image.png
## 
## > contour(x, y, volcano, levels=seq(90, 200, by=5), add=TRUE, col="black")
## 
## > axis(1, at=x.at)
## 
## > axis(2, at=y.at)
## 
## > box()
## 
## > title(main="Maunga Whau Volcano \n col=gray(100:200/200)", font.main=4)
## 
## > ## Filled Contours are even nicer sometimes :
## > example(filled.contour)
## 
## flld.c> require("grDevices") # for colours
## 
## flld.c> filled.contour(volcano, asp = 1) # simple
image.png
## 
## flld.c> x <- 10*1:nrow(volcano)
## 
## flld.c> y <- 10*1:ncol(volcano)
## 
## flld.c> filled.contour(x, y, volcano, color = function(n) hcl.colors(n, "terrain"),
## flld.c+     plot.title = title(main = "The Topography of Maunga Whau",
## flld.c+     xlab = "Meters North", ylab = "Meters West"),
## flld.c+     plot.axes = { axis(1, seq(100, 800, by = 100))
## flld.c+                   axis(2, seq(100, 600, by = 100)) },
## flld.c+     key.title = title(main = "Height\n(meters)"),
## flld.c+     key.axes = axis(4, seq(90, 190, by = 10)))  # maybe also asp = 1
image.png
## 
## flld.c> mtext(paste("filled.contour(.) from", R.version.string),
## flld.c+       side = 1, line = 4, adj = 1, cex = .66)
## 
## flld.c> # Annotating a filled contour plot
## flld.c> a <- expand.grid(1:20, 1:20)
## 
## flld.c> b <- matrix(a[,1] + a[,2], 20)
## 
## flld.c> filled.contour(x = 1:20, y = 1:20, z = b,
## flld.c+                plot.axes = { axis(1); axis(2); points(10, 10) })
image.png
## 
## flld.c> ## Persian Rug Art:
## flld.c> x <- y <- seq(-4*pi, 4*pi, len = 27)
## 
## flld.c> r <- sqrt(outer(x^2, y^2, "+"))
## 
## flld.c> filled.contour(cos(r^2)*exp(-r/(2*pi)), axes = FALSE)
image.png
## 
## flld.c> ## rather, the key *should* be labeled:
## flld.c> filled.contour(cos(r^2)*exp(-r/(2*pi)), frame.plot = FALSE,
## flld.c+                plot.axes = {})
image.png

數(shù)據(jù)讀寫

## read csv file 程序中的選項header=TRUE指明第一行作為變量名行脓诡, 選項as.is=TRUE說明字符型列要原樣讀入而不是轉(zhuǎn)換為因子(factor)。技巧:read.csv()的一個改進版本是readr擴展包的read_csv()函數(shù)媒役, 此函數(shù)讀入較大表格速度要快得多祝谚, 而且讀入的轉(zhuǎn)換設(shè)置更傾向于不做不必要的轉(zhuǎn)換。 但是酣衷, 這兩種輸入方法的默認中文編碼可能不一樣交惯。
tax.tab <- read.csv("taxsamp.csv",header = T,as.is = T)

### 分類統(tǒng)計變量頻數(shù)
table(tax.tab$征收方式)
## 
##     查帳征收 定期定額征收 定期定率征收 
##           31           16            2
table(tax.tab[["申報渠道"]])
## 
## 大廳申報 網(wǎng)上申報 
##       18       31
## 交叉取頻數(shù)
table(tax.tab[["征收方式"]],tax.tab[["申報渠道"]])
##               
##                大廳申報 網(wǎng)上申報
##   查帳征收            9       22
##   定期定額征收        9        7
##   定期定率征收        0        2
## 制表
knitr::kable(table(tax.tab[["征收方式"]], tax.tab[["申報渠道"]]) )
大廳申報 網(wǎng)上申報
查帳征收 9 22
定期定額征收 9 7
定期定率征收 0 2
## 數(shù)值變量統(tǒng)計 中位數(shù)是從小到大排序后排在中間的值。 四分之一和四分之三分位數(shù)類似。
## 如果數(shù)據(jù)中有缺失值席爽, 可以刪去缺失值后計算統(tǒng)計量意荤, 這時在mean, sd等函數(shù)中加入na.rm=TRUE選項。
summary(tax.tab[["營業(yè)額"]])
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##       0     650    2130  247327    9421 6048000
mean(tax.tab[["營業(yè)額"]])
## [1] 247327.4
sd(tax.tab[["營業(yè)額"]], na.rm=T)
## [1] 1036453
source("ssq.r")

參考材料:https://www.math.pku.edu.cn/teachers/lidf/docs/Rbook/html/_Rbook/intro-example.html

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末只锻,一起剝皮案震驚了整個濱河市玖像,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌齐饮,老刑警劉巖捐寥,帶你破解...
    沈念sama閱讀 216,591評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異祖驱,居然都是意外死亡上真,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,448評論 3 392
  • 文/潘曉璐 我一進店門羹膳,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人根竿,你說我怎么就攤上這事陵像。” “怎么了寇壳?”我有些...
    開封第一講書人閱讀 162,823評論 0 353
  • 文/不壞的土叔 我叫張陵醒颖,是天一觀的道長。 經(jīng)常有香客問我壳炎,道長泞歉,這世上最難降的妖魔是什么跟衅? 我笑而不...
    開封第一講書人閱讀 58,204評論 1 292
  • 正文 為了忘掉前任嫂拴,我火速辦了婚禮,結(jié)果婚禮上枪芒,老公的妹妹穿的比我還像新娘铲球。我一直安慰自己挺庞,他們只是感情好,可當我...
    茶點故事閱讀 67,228評論 6 388
  • 文/花漫 我一把揭開白布稼病。 她就那樣靜靜地躺著选侨,像睡著了一般。 火紅的嫁衣襯著肌膚如雪然走。 梳的紋絲不亂的頭發(fā)上援制,一...
    開封第一講書人閱讀 51,190評論 1 299
  • 那天,我揣著相機與錄音芍瑞,去河邊找鬼晨仑。 笑死,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的寻歧。 我是一名探鬼主播掌栅,決...
    沈念sama閱讀 40,078評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼码泛!你這毒婦竟也來了猾封?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,923評論 0 274
  • 序言:老撾萬榮一對情侶失蹤噪珊,失蹤者是張志新(化名)和其女友劉穎晌缘,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體痢站,經(jīng)...
    沈念sama閱讀 45,334評論 1 310
  • 正文 獨居荒郊野嶺守林人離奇死亡磷箕,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,550評論 2 333
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了阵难。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片岳枷。...
    茶點故事閱讀 39,727評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖呜叫,靈堂內(nèi)的尸體忽然破棺而出空繁,到底是詐尸還是另有隱情,我是刑警寧澤朱庆,帶...
    沈念sama閱讀 35,428評論 5 343
  • 正文 年R本政府宣布盛泡,位于F島的核電站,受9級特大地震影響娱颊,放射性物質(zhì)發(fā)生泄漏傲诵。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,022評論 3 326
  • 文/蒙蒙 一箱硕、第九天 我趴在偏房一處隱蔽的房頂上張望拴竹。 院中可真熱鬧,春花似錦颅痊、人聲如沸殖熟。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,672評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽菱属。三九已至,卻和暖如春舰罚,著一層夾襖步出監(jiān)牢的瞬間纽门,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,826評論 1 269
  • 我被黑心中介騙來泰國打工营罢, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留赏陵,地道東北人饼齿。 一個月前我還...
    沈念sama閱讀 47,734評論 2 368
  • 正文 我出身青樓,卻偏偏與公主長得像蝙搔,于是被迫代替她去往敵國和親缕溉。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 44,619評論 2 354