如何透過重複行數來增加 R 資料框的長度?
如果我們堅信新的資料收集將產生相同型別的資料,那麼我們可能希望在 R 中用更多行擴充套件我們的資料框。雖然,這並不推薦,因為由於這個過程,我們失去了資料的無偏性,但這樣做是為了節省在新的資料收集上投入的時間和金錢。在 R 中,我們可以使用 rep 和 seq_len 函式來重複 R 資料框的行數。
示例
考慮以下資料框 -
> x1<-c("Fruits","Vegetables","Dry Fruits","Dairy")
> x2<-c(2,5,6,3)
> df<-data.frame(x1,x2)
> df
x1 x2
1 Fruits 2
2 Vegetables 5
3 Dry Fruits 6
4 Dairy 3重複行數兩次,但一次重複跟隨另一次 -
> df[rep(seq_len(nrow(df)),times=2),] x1 x2 1 Fruits 2 2 Vegetables 5 3 Dry Fruits 6 4 Dairy 3 1.1 Fruits 2 2.1 Vegetables 5 3.1 Dry Fruits 6 4.1 Dairy 3
重複行數五次,但一次重複跟隨另一次 -
> df[rep(seq_len(nrow(df)),times=5),] x1 x2 1 Fruits 2 2 Vegetables 5 3 Dry Fruits 6 4 Dairy 3 1.1 Fruits 2 2.1 Vegetables 5 3.1 Dry Fruits 6 4.1 Dairy 3 1.2 Fruits 2 2.2 Vegetables 5 3.2 Dry Fruits 6 4.2 Dairy 3 1.3 Fruits 2 2.3 Vegetables 5 3.3 Dry Fruits 6 4.3 Dairy 3 1.4 Fruits 2 2.4 Vegetables 5 3.4 Dry Fruits 6 4.4 Dairy 3
重複每一行,次數相同 -
> df[rep(seq_len(nrow(df)),each=5),] x1 x2 1 Fruits 2 1.1 Fruits 2 1.2 Fruits 2 1.3 Fruits 2 1.4 Fruits 2 2 Vegetables 5 2.1 Vegetables 5 2.2 Vegetables 5 2.3 Vegetables 5 2.4 Vegetables 5 3 Dry Fruits 6 3.1 Dry Fruits 6 3.2 Dry Fruits 6 3.3 Dry Fruits 6 3.4 Dry Fruits 6 4 Dairy 3 4.1 Dairy 3 4.2 Dairy 3 4.3 Dairy 3 4.4 Dairy 3
重複行數,次數不同 -
> df[rep(seq_len(nrow(df)),times=c(2,3,4,5)),] x1 x2 1 Fruits 2 1.1 Fruits 2 2 Vegetables 5 2.1 Vegetables 5 2.2 Vegetables 5 3 Dry Fruits 6 3.1 Dry Fruits 6 3.2 Dry Fruits 6 3.3 Dry Fruits 6 4 Dairy 3 4.1 Dairy 3 4.2 Dairy 3 4.3 Dairy 3 4.4 Dairy 3
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP