... <看更多>
Search
Search
#1. 【R語言】簡單抽樣. Sample() | by 彭奕森Eason Peng | Medium
R 語言中是很簡單,用sample() 就能夠達成。以投骰子為例, ... 因為sample() 函數的返回值是一個隨機確定的數字,如果每再反覆執行,每次都會得到不同的結果。
用法 : sample(x, size, replace). 參數: x:表示向量或正整數或DataFrame size:表示要采集的樣本大小 replace:表示邏輯值。如果為TRUE,樣本可能有多個相同的值.
在医学统计学或者流行病学里的现场调查、样本选择经常会提到一个词:随机抽样。随机抽样是为了保证各比较组之间均衡性的一个很重要的方法。
#4. Chapter 7 基本統計函式| R 資料科學與統計 - Bookdown
{R} 有許多統計函式, 可以對向量物件進行統計分析, {R} 內建所有常見的基礎敘述統計量, 例如累加與乘積 ... 在{R} 中有一個常用的隨機抽樣函式, sample() , 用法如下.
“replace”就是重複的意思。即可以重複對元素進行抽樣,也就是所謂的有放回抽樣。我們看上面的結果,元素4在5次隨機抽樣的過程中被抽取了兩次。
#6. 第17 天:實用R 語言技巧彙整
實用技巧. 我們可以運用 sample() 函數協助我們從一個向量中抽樣,例如從1 到10 這10 個數字中抽樣5 ...
sample 基本用法参数解释:x表示所要抽样数据,size表示抽样个数,replace为T表示采取有重复的抽样代码目的:在1到10间有放回的随机抽取5个数对数据框 ...
#10. R语言base包sample函数使用说明 - 爱数吧
sample 从x元素中提取指定大小的样本,使用替换或不替换。 语法\用法:. sample(x, size, replace = FALSE, prob = NULL) sample.int(n, size ...
#11. R語言入門之使用函數sample進行抽樣 - 每日頭條
第二個代碼表示用700和y向量中的每一個元素進行比較,將每次比較結果較小者輸出。 這就是pmax/pmin的用法,p在這裡表示「parallel」,可以理解為對向量做 ...
#12. R语言中set.seed函数的作用- 小鲨鱼2018 - 博客园
R 语言中set.seed函数的作用是保证两次随机抽样的结果一致。 1、不使用set.seed函数的情况下> sample(1:8, 3) ## 从1~8中随机抽取3个数字[1] 3 7 4.
#13. r语言sample函数用法-掘金 - 稀土掘金
r 语言sample函数用法技术、学习、经验文章掘金开发者社区搜索结果。掘金是一个帮助开发者成长的社区,r语言sample函数用法技术文章由稀土上聚集的技术大牛和极客共同 ...
#14. R语言中sample函数 - 51CTO博客
R 语言中sample函数,1、随机抽样>a<-1:10>sample(a,5)[1]945106>sample(a,5,replace=T)[1]107534>sample(a,5,replace=T)##有放回 ...
#15. 42 随机模拟| R语言教程
dplyr包的 sample_n() 函数与 sample() 类似, 但输入为数据框, 输出为随机抽取的数据框行子集。 42.3 随机模拟示例. 42.3.1 估计期望值. 设随机变量或随机向量 ...
#16. R「survey」套件簡介-- 以104 年網路沉迷研究為例 - SRDA
這部分我們將採用sample()函數來進行簡單隨機抽樣,該函數也是在R 軟體中 ... 在說明survey 套件的使用方法之前,我們先以簡單隨機抽樣樣本中的變數.
#17. R语言—seq()函数、sample()函数、runif()函数 - 知乎专栏
参考:R语言中seq函数的用法_记录本的博客-CSDN博客_seq函数. (笔记整理较匆忙,若未标明出处,抱歉请联系我,会及时补充哦). 编辑于2023-03-20 00:27・IP 属地河南.
#18. R筆記--(3)套件與函式 - RPubs
串接:paste(), append(); 合併:rbind(), cbind(); 數列:sample(), ... 以下將會介紹R裡面一些實用的函式,以及如何根據自己的需求,搜尋到對應的 ...
#19. Day 30- R語言假設檢定(Hypothesis testing) 函數練習 - iT 邦幫忙
今天是本篇鐵人賽的最後一篇了,那就來談談在R裡面執行假設檢定吧ˊˇˋ 假設檢定在統計學中有 ... x <- sample(1:100, size = 10, replace = FALSE) t.test(x, mu = 30).
#20. 在R语言中实现简单随机抽样 - 翔宇亭IT乐园
R 语言中随机抽样函数sample简介 ... 参数的含义如下:. x:为向量,表示抽样的总体,或者是一个正整数,表示样本总体为1~n;. size:为样本容量,即要抽取的 ...
#21. R 機率分佈與線性模型 - G. T. Wang
sample 是一個用來產生隨機變數的函數,但是它的使用方式比較特殊。如果只指定單一個整數的參數 n ,它會傳回從 1 到 n 的隨機排列組合: sample(6)
#22. random --- 生成偽隨機數— Python 3.11.2 說明文件
進位互補乘法(Complementary-Multiply-with-Carry) 用法,可作為隨機數產生器的一個可相容 ... r = len(pool) if r is None else r return tuple(random.sample(pool, ...
#23. 抽样三步曲之一:R语言进行随机抽样sampling - 粉丝日志
在R语言中,我们可以用基础包的sample()函数进行随机抽样,使用自带的鸢尾花数据集iris。 使用sample()函数,总体数据为N=150个,抽取出样本s=15个。 # ...
#24. 獨立樣本t檢定(Independent Sample t test)-統計說明與SPSS操作
獨立樣本t檢定用於比較兩樣本的平均數是否有顯著差異,以下為其公式、使用方法及SPSS操作。 一、使用狀況. Two sample t-test:比較兩組樣本的平均值 ...
#25. R程式設計 - 吳漢銘
計算方式如右表,請寫一R函式,將某. 同學之各科修課成績百分數score轉成. 等級及GPA。 > set.seed(12345). > score <- sample(0:100, 10, replace=T). > ...
#26. R 使用t 檢定判斷平均數是否相同教學與範例 - Office 指南
使用R 的 t.test 函數進行單一樣本、獨立雙樣本與成對樣本的t 檢定,檢驗母體平均數 ... confidence interval: 164.3532 176.6468 sample estimates: mean of x 170.5.
#27. [R]常用亂數函數的數組產生測試| Ting I 的程式碼集中營 - - 點部落
R 的亂數函數測試. ... 產生亂數組的客製函數 #type : 亂數類型 #count : 亂數數量 generate_random_type <- function(type, count) { #random用法 ...
#28. 10 資料探勘| 資料科學與R語言 - Yi-Ju Tseng
在R中,最基本的簡單線性迴歸分析為 lm() ,使用方法為 lm(formula,data=資料名稱) ... set.seed(1234) dataMatrix <- as.matrix(dataFrame)[sample(1:12),] kmeansObj ...
#29. R:筛选样本 - OBHRM百科
随机抽取需要使用sample()函数,sample()函数的使用方法,可以在R控制台输入:? sample,了解具体的使用方法。 如果您有一个数据框mydata,现在需要随机从里头抽取100 ...
#30. R 語言學習心得-基礎篇3 - HackMD
統計函數範例3 · pnorm() : 小於等於某數所累積的機率 · pnorm()是左尾累積 · sample() : 產生隨機亂數.
#31. 語言入門
R 是一個開放的程式語言(Open Source),藉由指令宣告的方式來做統計運算. 分析與視覺化的資料繪圖。 ... 樣,此為樣本函數(sampling functions)的功能使用。範例如下:.
#32. Python random.sample() - 极客教程
sample ()是Python中随机模块的一个内置函数,它返回一个从序列即列表、元组、字符串或集合中选择的特定长度的项目列表。用于无替换的随机抽样。
#33. 第5 章: 常用的R 程式語言5
在R 中有一個常用的隨機抽樣函式, sample(), 用法如下. > sample(x, size, replace = FALSE, prob = NULL). 其中引數 x x 為一長度大於1 的任意向量, ...
#34. Python random() 函数 - 菜鸟教程
()') # 多个字符中生成指定数量的随机字符: print random.sample('zyxwvutsrqponmlkjihgfedcba',5) # 从a-zA-Z0-9生成指定数量的随机字符: ran_str ...
#35. Random.Next 方法(System) - Microsoft Learn
下列範例衍生類別, Random 以產生亂數序列,其分佈與基類方法所產生的Sample 統一分佈不同。 它會覆寫Sample 方法來提供亂數的分佈,並覆寫Random.Next 方法以使用亂數 ...
#36. 估計與檢定
(one sample. T-test). 用來檢定一組含 個樣本且平均值為 ... (two- sample. T-test) ... 由表2的資料,利用R的卡方檢定之指令“chisq.test”,所得結果 $Q=0.47$ , $p$ ...
#37. R語言正態分佈 - 億聚網
我們繪製直方圖以顯示生成數字的分佈。 setwd("F:/worksp/R") # Create a sample of 50 numbers which are normally distributed. y <- rnorm(50) ...
#38. 標準差- 维基百科,自由的百科全书
標準差,又稱標準偏差、均方差(英語:standard deviation,縮寫SD,符號σ),在概率統計中最常 ... 的样本(sample)范围内考量。 標準差可以當作不確定性的一種測量。
#39. random — 你所不知道的Python 標準函式庫用法02 - Louie Lu
04. random.sample(population, k). 回傳長度為 k 且元素唯一的list。此為非重置抽樣(sampling without replacement)。 重置 ...
#40. 比率估计与回归估计抽样技术中五个非常实用的R函数
The R functions (programs) will provide a great convenience for the users who need to use ratio estimation and regression estimation sampling techniques to ...
#41. R commands(11.09.13) 指令用法簡介
指令. 用法簡介. 基本操作 source("路徑"). 載入外部程式 sink("路徑")+sink(). 紀錄程式執行結果 demo(套件). 展示套件的示範功能 example(函數).
#42. R语言二项分布 - 易百教程
setwd("F:/worksp/R") # Create a sample of 50 numbers which are incremented by 1. x <- seq(0,50,by = 1) # Create the binomial distribution. y <- dbinom(x,50 ...
#43. random sample - 随机抽样调查-新东方在线英语词典
random sample是什么意思?random sample怎么读?新东方在线字典为用户提供单词random sample的释义、random sample的音标和发音、random sample的用法、例句、词组、 ...
#44. R语言:基本数据、数据处理- 文章详情
日期值通常以字符串的形式输入到R中,然后转化为以数值形式存储的日期变量 ... 用法:sample() 函数中的个参数是一个由要从中抽样的元素组成的向量。
#45. R中paste cat和sink的用法- 腾讯云开发者社区
collapse 是把结果进行处理,也可以认为怎么来对结果进行折叠。 通过具体例子来看 sep 和 collapse 参数. > paste('Sample ...
#46. R常见问题解答153 分钟学会
R 是一个很庞大的体系,在CRAN 的Task Views 上可以清楚地看到贝叶斯推断、聚类分 ... sample(x,n, replace = T ,prob = p) 以概率p,放回的从x 中抽取n 项.
#47. [心得] 資料整理套件介紹-第二章dplyr(上) - 看板R_Language
再介紹一些這些函數的其他用法` R dt = data.table(V1 = rpois(20, 3), V2 = sample(c("g1", "g2"), 20, 1), V3 = rnorm(20), V4 = rgamma(20, 5, ...
#48. R语言cannot take a sample larger than the population when ...
那么,sample()和runif()不同系统、R版本的结果是否可能不一致呢?当... db2 replace函数的用法_R语言入门之使用函数sample进行抽样.
#49. R統計分析與資料探勘入門—以鳶尾花資料集為例 - 計資中心
敘述統計這個R內建的鳶尾花(iris)資料集是非常著名的生物資訊資料集之一,取自美國加州大學歐文分校的機械學習資料庫http://archive.ics.uci.edu/ml/ ...
#50. R語言之決策樹簡介 - 叡揚資訊
以下透過R語言來進行實踐:以iris鳶尾花的資料集為例。 ... set.seed(123) > test_index <- sample(1:n,test_n) > test_data <- iris[test_index,] > ...
#51. 關於Sample的意思和用法的提問 - HiNative
A: Got it, thank you. Yes, it's a grammatically correct phrase, and yes, I'm sure it's referring to copyright on music samples. A "claim" in this case is the ...
#52. 連續資料相關性分析(The Correlation of Continuous Data)
其中cov 為共變異數(covariance), σX 為x 的標準差,μX 為x 的平均值, E 為期望值。 若對於單一樣本(sample),其定義為. r=Σ ...
#53. r ? <- $ () [] {} [[ @ :: 常用特殊運算子(operators) - RWEPA
<-為指派運算子, 將右邊的運算結果指派至左邊物件, 強烈建議指派運算子不要使用等號(=), 以免與函數中的參數相混淆. > lotto <- sample(49,6) > ...
#54. [R 語言] 用R 繪製統計品質管制圖(qcc package) - April Yang
簡介qcc; 下載qcc; 用法. Shewhart charts (修華特管制圖); Operating characteristic curves (OC 曲線); Process capability analysis (製程能力分析) ...
#55. 推荐算法-R相关包使用方法及案例解析
class(MovieLense) # class(MovieLenseMeta) ## 943 x 1664 rating matrix of class 'realRatingMatrix' with 99392 ratings. image(sample(MovieLense,500),main="Raw ...
#56. [R]Chi-square 卡方檢定 - Wenwu's blog
... 最入門的就是卡方檢定今天要介紹如何用R來使用卡方檢定三種卡方檢定卡 ... 首先我們紀錄每次投骰子的結果,總共六百次(使用sample.int產生投骰子 ...
#57. R如何实现欧式距离等计算 - CDA数据分析师
在R中计算距离的函数为dist(),比较直接的用法是dist(x,me. ... 了。dist默认就是算欧式距离,算完后得到一个所有距离的矩阵,假定你需要sample 504(即你的data中第一 ...
#58. 【R语言实用技巧】随机排序、随机抽样与分层抽样
自带的 sample 函数是实现随机抽样最基础的函数,以此为基础,dplyr中的sample_n与sample_frac,以及doBy中的sampleBy函数能够实现更复杂的一些需求.
#59. 機率統計-- 使用R 軟體 - SlideShare
... 操作為了說明R 軟體的用法,並用以學習機率統計的概念,本系列文章將運用R ... 函數」 的方式查詢某函數的功能,因此當我們在R 軟體中鍵入?sample ...
#60. R语言统计入门-第八章 - Bionew
1-sample proportions test with continuity correction ## ## data: 39 out of 215, null probability 0.15 ## X-squared = 1.425, df = 1, ...
#61. 假設檢驗(檢定) - 陳鍾誠的網站
本文改自:(徐俊曉) 統計學與R讀書筆記第五版 ... percent confidence interval: -0.21865305 0.05585082 sample estimates: mean of x -0.08140112 ...
#62. decode函数是什么意思,decode函数用法-易企推百科
decode函数是什么意思,decode函数用法第五十一章SQL函数DECODE计算给定 ... 17,'Teen',18,'Teen',19,'Teen', 'Adult') AS AgeBracket FROM Sample.
#63. 【Android】ListView 搭配ArrayAdapter 教學 - 學程式很簡單
ArrayAdapter (此篇) – ListView 簡易用法; SimpleCursorAdapter; SimpleAdapter – ListView 進階用法-,簡易客製化ListView Item樣式 ...
#64. sklearn.linear_model.LinearRegression
Predict using the linear model. Parameters: Xarray-like or sparse matrix, shape (n_samples, n_features). Samples.
#65. Gdal save tiff - AISC 2022 MIDTERM
Example The following would burn all polygons from mask.shp into the RGB TIFF ... 关于使用方法,网上一搜索就有很多,主要是经过gdal初始化、获取地形文件信息后 ...
#66. Quickstart — Requests 2.28.2 documentation - Read the Docs
r = requests.get('https://api.github.com/events'). Now, we have a Response object called r . ... For example, this is how you make an HTTP POST request:.
#67. R語言第二堂課數字.md - gists · GitHub
... 回#從指定範圍隨機取值sample(c(1,100),3,replace = TRUE) #標準常態分配rnorm(4) ... Random.seed = oldseed runif(3) #如果在R session中未使用隨機數生成器,則 ...
#68. Python if, if...else Statement (With Examples) - Programiz
In this tutorial, you will learn about the Python if...else statement with the help of examples to create decision-making programs.
#69. Text in Compose | Android Developers
Use the same brush for both parts of a text, and change the alpha parameter in the corresponding span. In the code sample, the first span of text displays at ...
#70. Get started with TensorBoard - TensorFlow
On this page · Using TensorBoard with Keras Model.fit() · Using TensorBoard with other methods · TensorBoard.dev: Host and share your ML experiment ...
#71. Python String endswith() Method - W3Schools
Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, Python, PHP, Bootstrap, Java, ...
#72. golang exec command no such file or directory. ru/nn18nm ...
Start will return that same error. stm32 hal can bus example Golang ... 的使用方法, 可以查看下面的Golang Buildfile类(方法)源码代码实例,从而了解它的用法。
#73. APA 文獻引用之中文書寫格式與圖表的呈現
Bock, B. C., Graham, A. L., Sciamanna, C. N., Krishnamoorthy, J., Whiteley, J.,. Carmona-Barros, R., … Abrams,D. B. (2004). Nicotine and Tobacco. Research, 6, ...
#74. pandas.DataFrame.merge — pandas 1.5.3 documentation
A named Series object is treated as a DataFrame with a single named column. The join is done on columns or indexes. If joining columns on columns, the DataFrame ...
#75. numpy.random.randint — NumPy v1.24 Manual
Output shape. If the given shape is, e.g., (m, n, k) , then m * n * k samples are drawn. Default is None, in which case a single value is returned.
#76. Legend In Matlab
For example: hold on for k = 1:10 txt = ['X = ',num2str (k)];. ... the location, setting. matlab 中legend 函数在添加图例时的使用方法功能在图形上添加图例。
#77. sprintf - Manual - PHP
Returns a string produced according to the formatting string format . Parameters ¶. format. The format string is composed of zero or more directives: ordinary ...
#78. Zsqrmt - MutuoRe.it
For example, to calculate the square root of 99 which notes 9 enter sqrt ( 99), after . ... 下面的实例演示了 sqrt () 函数的用法。
#79. Configure Grafana | Grafana documentation
It contains all the settings commented out. Copy sample.ini and name it custom.ini . macOS. By default, the configuration file is located at / ...
#80. Tasks in Visual Studio Code
These tools are mostly run from the command line and automate jobs inside and outside the inner software development loop (edit, compile, test, and debug).
#81. addmodulescore
The example below defines some simple signatures, and applies them on ... 为基因集进行打分常见的富集分析软件GSVA,今天我们来看看Seurat这个函数的用法和意义。
#82. LaTeX/Mathematics - Wikibooks, open books for an open world
Help and Recommendations. FAQ · Tips and Tricks. Appendices. Authors · Links · Package Reference · Sample LaTeX documents · Index · Command Glossary.
#83. docker build
The docker build command builds Docker images from a Dockerfile and a “context”. A build's context is the set of files located in the specified PATH or URL .
#84. Aggregations | Elasticsearch Guide [8.6] | Elastic
Elastic Cloud. Maximize value and optimize your experience. Deploy everything Elastic has to offer across any cloud, in minutes.
#85. Frunnable Ue4
I updated this example based on how FRunnable is used in the Unreal source code. ... 实现了一套多线程机制(应该是从UE3时代就有了,未考证),用法上很像Java。
#86. Learn LaTeX in 30 minutes - Overleaf
To produce a visible, typeset document, your LaTeX file is processed by a piece of software called a TeX engine which uses the commands embedded in your text ...
#87. Matlab Place - Schreibwerkstatt fantastica4
Matlab PlaceMATLAB is a programming platform for scientists and engineers. Smoking is a social trend that is prevalent around the world, particularly in ...
#88. Extended Syntax - Markdown Guide
MultiMarkdown · R Markdown. Markdown Processors. There are dozens of Markdown processors available. Many of them allow you to add extensions that enable ...
#89. His Matlab - Baustoffe Niederrhein
相关推荐 情态动词 用法(flash) 本课件是有关 情态动词 用. Need help trolling my prof with MatLab : r/EngineeringStudents. m — graphs ellipsoids and their ...
#90. Lovelace Ui Hassio
Home Assistant Lovelace UI基本用法本文内容根据官方文档总结,感兴趣的可直接阅览官方 ... add-ons, custom Lovelace cards & plugins, cookbooks, example setups, ...
#91. 化妝品到期日點睇?各大品牌瓶底編號透露生產日期、保存期限
不妨參考以下10大推薦、學習選出適合自己髮質的髮尾油,以及正確用法。 閱讀全文.
#92. git-diff Documentation - Git
Select only files that are Added ( A ), Copied ( C ), Deleted ( D ), Modified ( M ), Renamed ( R ), have their type (i.e. regular file, symlink, submodule, …) ...
#93. Basics - styled-components
Motivation. styled-components is the result of wondering how we could enhance CSS for styling React component systems. By focusing on a single use case we ...
#94. COCA - English-Corpora
[Davies] 1.1 billion word corpus of American English, 1990-2010. Compare to the BNC and ANC. Large, balanced, up-to-date, and freely-available online.
#95. Browse Poems | Poetry Foundation
Ancestors' wildest dreams. By Kinsale Drake. r drunk on the sticky floor ... when I was young, I wanted to name paint samples. Appeared in Poetry Magazine ...
#96. Vuelidate | A Vue.js model validation library
Submit! Code sample. JavaScript. import { required, minLength } ...
#97. add_action() | Function - WordPress Developer Resources
Adds a callback function to an action hook. Contents. Description; Parameters; Return; More Information. Usage. Source; Related. Uses; Used By.
#98. 第4 章Sampling And Sample Distribution | 应用统计学与R语言 ...
本篇是第四章,内容主要是抽样方法与抽样分布。这一章内容比较多(从抽样方法一直到许多分布函数,尤其是介绍了四个重要分布——正态分布、卡方分布、t分布、F分布,以及部分 ...
r sample 用法 在 [心得] 資料整理套件介紹-第二章dplyr(上) - 看板R_Language 的美食出口停車場
這章重點放在dplyr
plyr與dplyr有不少函數是重疊的
不過都會以dplyr為主
plyr跟dplyr有一些名字不同,但功能相似的函數
我會一併介紹
先列一下這章要介紹的函數 (沒標註的就是來自dplyr)
A. 基本整理的函數:arragnge, filter, mutate, select, group_by, summarise, n
B. 增併rownames為變數:add_rownames, plyr:::name_rows
C. list to data.frame:as_data_frame
D. by var 合併函數:join, plyr:::join, data.table:::merge, base:::merge
E. col/row 合併函數:bind_rows, data.table:::rbindlist, bind_cols
F. 取唯一列:distinct, data.table:::unique
G. 列行運算:rowwise, plyr:::colwise
H. 值映射(對應修改):plyr:::mapvalues, plyr:::revalue
I. 其他函數:summarise_each, mutate_each
J. 特殊函數:plyr:::here
1. 基本整理函數
arrange: 根據你選定的變數做排列 (可以是多個變數)
filter: 根據你設定的條件做row 篩選(or selection)
mutate: 根據你給定的值賦予新變數,或是變更舊變數
select: 根據給定的變數名稱做選擇,也可以做刪除變數
group_by: 根據給定變數做group,以銜接summarise
summarise: 資料整併
n: 計算資料個數
用一個簡單例子來展示用法:
` R
set.seed(100)
(dt = data.table(V1 = rpois(5, 3),
V2 = sample(c("g1", "g2"), 5, 1), V3 = rnorm(5)))
# V1 V2 V3
# 1: 2 g1 0.3186301
# 2: 2 g2 -0.5817907
# 3: 3 g1 0.7145327
# 4: 1 g2 -0.8252594
# 5: 3 g1 -0.3598621
dt %>% arrange(V1, V2, V3)
# V1 V2 V3
# 1: 1 g2 -0.8252594
# 2: 2 g1 0.3186301
# 3: 2 g2 -0.5817907
# 4: 3 g1 -0.3598621
# 5: 3 g1 0.7145327
dt %>% filter(V1 <= 2, V3 < 0)
# V1 V2 V3
# 1: 2 g2 -0.5817907
# 2: 1 g2 -0.8252594
dt %>% mutate(V5 = V1 * V3, V6 = substr(V2, 2, 2),
V7 = round(V3), V8 = 1L, V3 = V3 **2)
# V1 V2 V3 V5 V6 V7 V8
# 1: 2 g1 0.1015251 0.6372602 1 0 1
# 2: 2 g2 0.3384804 -1.1635814 2 -1 1
# 3: 3 g1 0.5105570 2.1435981 1 1 1
# 4: 1 g2 0.6810531 -0.8252594 2 -1 1
# 5: 3 g1 0.1295008 -1.0795864 1 0 1
dt %>% select(V1, V2)
# V1 V2
# 1: 2 g1
# 2: 2 g2
# 3: 3 g1
# 4: 1 g2
# 5: 3 g1
dt %>% group_by(V2) %>% summarise(size_g = n(), m_V3 = mean(V3),
s_V1 = sum(V1))
# V2 size_g m_V3 s_V1
# 1 g1 3 0.2244336 8
# 2 g2 2 -0.7035251 3
`
上面的例子是一些簡單運用的範例
先介紹一下tbl_df, tbl_dt的class
tbl_df跟tbl_dt只會列出一部分的資料
做操作時比較不會因為太多資料的輸出造成當機
要更改列出的資料量,可以這樣做
` R
set.seed(100)
(dt = data.table(V1 = rpois(50, 3), V2 = sample(c("g1", "g2"), 50, 1),
V3 = rnorm(50))) %>% tbl_dt(FALSE)
# V1 V2 V3
# 1 2 g1 -0.4470622
# 2 2 g1 -1.7385979
# 3 3 g1 0.1788648
# 4 1 g1 1.8974657
# 5 3 g2 -2.2719255
# 6 3 g1 0.9804641
# 7 4 g1 -1.3988256
# 8 2 g1 1.8248724
# 9 3 g2 1.3812987
# 10 1 g1 -0.8388519
# .. .. .. ...
print(dt, n = 5)
# V1 V2 V3
# 1 2 g1 -0.4470622
# 2 2 g1 -1.7385979
# 3 3 g1 0.1788648
# 4 1 g1 1.8974657
# 5 3 g2 -2.2719255
# .. .. .. ...
`
再介紹一些這些函數的其他用法
` R
dt = data.table(V1 = rpois(20, 3), V2 = sample(c("g1", "g2"), 20, 1),
V3 = rnorm(20), V4 = rgamma(20, 5, 3))
# 你可以直接用一個你想要使用的變數放入,不須先立變數
dt %>% arrange(V1*V3, V3)
dt %>% filter(abs(V1*V3) > 1)
# desc是dplyr的函數提供反向排列
dt %>% arrange(V1)
dt %>% arrange(desc(V1))
# 兩種做變數刪除的方式 (我偏好第二種)
dt %>% mutate(V4 = NULL)
dt %>% select(-V4)
# select 還有提供各種特別函數於select中使用
dt %>% select(starts_with("V"))
dt %>% select(ends_with("1"))
dt %>% select(contains("2"))
dt %>% select(matches("\\w\\d"))
dt %>% select(num_range("V", 1:2))
`
2. 增併rownames為變數
如標題所示,直接看範例
` R
dat = data.frame(A = 1:5, row.names = paste0("City_", LETTERS[1:5]))
dat %>% name_rows
dat %>% add_rownames
dat %>% add_rownames("city") # add_rownames可以改成你要的名稱
`
3. list to data.frame
as_data_frame提供比as.data.frame有效率的轉換方法
我之前也沒用過,不過看到manual寫到這個函數,就忍不住想分享一下
不過這個函數強迫list的element要有name,使用上要注意一下
` R
library(microbenchmark)
dat_list = lapply(rep(1e6, 200), rnorm)
names(dat_list) <- paste0("A", 1:200)
microbenchmark(
as_data_frame(dat_list),
as.data.frame(dat_list)
)
#Unit: milliseconds
# expr min lq mean median uq
# as_data_frame(dat_list) 1.22642 1.281156 1.418296 1.311944 1.339027
# as.data.frame(dat_list) 19.83196 20.199147 21.397833 20.350524 21.143335
# expr max neval
# as_data_frame(dat_list) 6.957693 100
# as.data.frame(dat_list) 33.307182 100
`
看起來是沒差很多啦(汗顏,可能資料不夠大
4. by var 合併函數
先介紹base的merge,這個函數是用來合併兩個data.frame
除了input的兩個data.frame,還有其他五個input (其他input之後再提)
a. by - 合併根據的變數
b. by.x - 合併根據的變數 於第一個data.frame的名稱
c. by.y - 合併根據的變數 於第二個data.frame的名稱
d. all.x - 是否保留來自第一個data.frame的values
e. all.y - 是否保留來自第一個data.frame的values
註:還有一個input是 all 可以一次控制all.x跟all.y
我用簡單的範例去介紹這幾個選項
` R
## 產生資料
set.seed(75)
(x = data.frame(cat1 = sample(c("A", "B", NA), 5, 1),
cat2 = sample(c(1, 2, NA), 5, 1), v = rpois(5, 3),
stringsAsFactors = FALSE))
# cat1 cat2 v
# 1 A 1 4
# 2 A 2 3
# 3 <NA> NA 4
# 4 B NA 4
# 5 A 1 4
(y = data.frame(cat1 = sample(c("A", "B", NA), 5, 1),
cat2 = sample(c(1, 2, NA), 5, 1), v = rpois(5, 3),
stringsAsFactors = FALSE))
# cat1 cat2 v
# 1 A 2 1
# 2 A 1 8
# 3 <NA> NA 2
# 4 B 2 5
# 5 <NA> 1 3
## 兩個data.frame的資料都不保留 (預設值)
merge(x, y, by = c("cat1","cat2"), all.x = FALSE, all.y = FALSE)
# cat1 cat2 v.x v.y
# 1 A 1 4 8
# 2 A 1 4 8
# 3 A 2 3 1
# 4 <NA> NA 4 2
## 保留第一個data.frame的全部資料
merge(x, y, by = c("cat1","cat2"), all.x = TRUE, all.y = FALSE)
# cat1 cat2 v.x v.y
# 1 A 1 4 8
# 2 A 1 4 8
# 3 A 2 3 1
# 4 B NA 4 NA
# 5 <NA> NA 4 2
## 保留第二個data.frame的全部資料
merge(x, y, by = c("cat1","cat2"), all.x = FALSE, all.y = TRUE)
# cat1 cat2 v.x v.y
# 1 A 1 4 8
# 2 A 1 4 8
# 3 A 2 3 1
# 4 B 2 NA 5
# 5 <NA> 1 NA 3
# 6 <NA> NA 4 2
## 保留兩個data.frame全部的資料
merge(x, y, by = c("cat1","cat2"), all.x = TRUE, all.y = TRUE)
# cat1 cat2 v.x v.y
# 1 A 1 4 8
# 2 A 1 4 8
# 3 A 2 3 1
# 4 B 2 NA 5
# 5 B NA 4 NA
# 6 <NA> 1 NA 3
# 7 <NA> NA 4 2
`
all.x跟all.y這四種組合分別對應到dplyr的四種join
a. inner_join - merge(..., all.x = FALSE, all.y = FALSE)
b. left_join - merge(..., all.x = TRUE , all.y = FALSE)
c. right_join - merge(..., all.x = FASLE, all.y = TRUE)
d. full_join - merge(..., all.x = TRUE , all.y = TRUE)
但是merge跟dplyr的join還是有些微不同
dplyr的join不會去比對by variable都是NA的情況
給一個例子就好
` R
inner_join(x, y, by = c("cat1","cat2"))
# cat1 cat2 v.x v.y
# 1 A 1 4 8
# 2 A 2 3 1
# 3 <NA> NA 4 2
# 4 A 1 4 8
`
PS: If you use dplyr 0.4.1, there is something wrong. You're gonna find the
output do not contain the line: 3 <NA> NA 4 2. Please update your dplyr
to 0.4.2 or higher version.
至於plyr:::join就沒有這個問題
` R
join(x, y, by = c("cat1","cat2"), 'inner')
# cat1 cat2 v v
# 1 A 1 4 8
# 2 A 2 3 1
# 3 <NA> NA 4 2
# 4 A 1 4 8
`
plyr:::join用法其實大同小異,它是用type去控制join方式
最後是data.table:::merge
` R
setDT(x)
setDT(y)
merge(x, y, by = c("cat1","cat2"))
# cat1 cat2 v.x v.y
# 1: NA NA 4 2
# 2: A 1 4 8
# 3: A 1 4 8
# 4: A 2 3 1
`
其實用法跟merge一模一樣,不贅述
介紹完by, all.x, 跟all.y之後,我們來介紹by.x跟by.y
用一個簡單例子:
` R
set.seed(75)
x = data.frame(cat1 = sample(c("A", "B", NA), 5, 1),
cat2 = sample(c(1, 2, NA), 5, 1), v = rpois(5, 3),
stringsAsFactors = FALSE)
y = data.frame(cat3 = sample(c("A", "B", NA), 5, 1),
cat4 = sample(c(1, 2, NA), 5, 1), v = rpois(5, 3),
stringsAsFactors = FALSE)
merge(x, y, by.x = c("cat1","cat2"), by.y = c("cat3","cat4"))
# cat1 cat2 v.x v.y
# 1 A 1 4 8
# 2 A 1 4 8
# 3 A 2 3 1
# 4 <NA> NA 4 2
`
我想這個例子已經很好說明了by.x跟by.y了
接著是再dplyr怎麼做?
` R
inner_join(x, y, by = c("cat1" = "cat3", "cat2" = "cat4"))
# cat1 cat2 v.x v.y
# 1 A 1 4 8
# 2 A 2 3 1
# 3 A 1 4 8
`
至於plyr:::join跟data.table:::merge就沒有支援這種功能了
dplyr還提供兩種join: semi_join跟anti_join
簡單說明一下,semi_join就是只保留第一個data.frame變數的inner_join
anti_join則semi_join沒有配對的組合
這兩個有興趣再去玩玩看,這裡就不提供例子了
最後是一個實際問題
我如果要merge超過三個的df怎麼辦?
可以參考一下 #1LaHm_aH (R_Language)
這裡完整介紹一下使用這幾個套件要怎麼解決
` R
DF_list = replicate(5, data.frame(cat1 = sample(c("A", "B"), 5, 1),
cat2 = sample(c(1, 2), 5, 1), v = rnorm(5)), simplify = FALSE)
# 下列兩種會變成橫表,每一個data.frame的v都會保留
Reduce(function(x, y) merge(x, y, by = c("cat1","cat2"), all=TRUE), DF_list)
Reduce(function(x, y) full_join(x, y, by = c("cat1","cat2")), DF_list)
# 只保留第一個data.frame的值
join_all(DF_list, by = c("cat1","cat2"), type = "full")
# 直表,保留全部的v,等同於全部做rbind
join_all(DF_list, by = c("cat1","cat2", "v"), type = "full")
`
其實這樣每一個方法的結果都會很混亂,非常不建議,除非你知道你目標是什麼
5. col/row 合併函數
bind_rows跟rbindlist其實就是在做 do.call(rbind, .)或是 Reduce(rbind, .)
只是這兩個function更加有效率
如果還不懂do.call(rbind, .)跟Reduce(rbind, .)再做什麼
剛好可以利用這個機會去弄懂他們在幹嘛
` R
DF_list = replicate(5, data.frame(cat1 = sample(c("A", "B"), 5, 1),
cat2 = sample(c(1, 2), 5, 1), v = rnorm(5)), simplify = FALSE)
bind_rows(DF_list)
rbindlist(DF_list)
`
bind_cols等同於 do.call(cbind, .)
`
DT_list = lapply(1:5, function(x) data.table(rnorm(5)) %>%
setnames(paste0("V", x)))
bind_cols(DT_list)
`
還有一半,我們留到下一章再討論。
[關鍵字]: dplyr
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 123.205.27.107
※ 文章網址: https://www.ptt.cc/bbs/R_Language/M.1437545676.A.A4B.html
第三章可能要拖到晚上了,現在有點累
... <看更多>