我想將幾個 data.frames 合二為一。所有 data.frames 共享一個相同的列。
有多種方法可以合并多個資料集,由于我使用的是這種方法,因此Reduce(function(...) merge(..., all=TRUE), list( ))我需要獲取環境中的 data.frames 串列。但是,每次我嘗試獲取它們的串列時,作為 data.frame 的功能都會消失,它們只保存為名稱。
這些是我的資料框:
file_1 <- women
file_2 <- women
colnames(file_2) <- c("height_2", "weight_2")
file_3 <- women
colnames(file_3) <- c("height_3", "weight_3")
file_4 <- women
colnames(file_4) <- c("height_4", "weight_4")
file_5 <- women
colnames(file_5) <- c("height_5", "weight_5")
由于我想合并它們,我需要為它們添加相同的列。使用第一行代碼,我列出了我在環境中擁有的變數(我只想要以名稱“file”開頭的 data.frames)
list_files <- grep("file",names(.GlobalEnv),value=TRUE)
for (file in list_files){
temp <- get(file)
# We add the column
temp$ID <- "col"
#we return the change in the file
assign(file, temp)
}
rm(temp) #we don't need it anymore.
但是,當我嘗試使用list_files(具有 data.frames 的名稱)來合并它們時,我沒有得到正確的 data.frame 合并。
DF_complete <- Reduce(function(...) merge(..., all=TRUE), list(list_files))
> class(DF_complete)
[1] "character"
另一方面,當我嘗試這段代碼(我自己撰寫所有資料幀)時,我得到了我想要的資料幀。
DF_2 <- Reduce(function(...) merge(..., all=TRUE), list(file_1, file_2, file_3, file_4, file_5))
class(DF2)
[1] "data.frame"
我想避免寫所有的data.frames。現在我有 5 個 data.frames,但是當我有超過 10 個時......這將是艱難的。為此,我想另辟蹊徑。
我看到了這篇文章,我試過了,但它們沒有保存為 data.frames。
list_df <- list(list_files)
> list_df
[[1]]
[1] "file_1" "file_2" "file_3" "file_4" "file_5"
class(list_df)
[1] "list"
有誰知道該怎么做?
首先十分感謝
uj5u.com熱心網友回復:
如果我們要合并的全域環境中有多個 data.frame,我們可以使用mgetand ls:
file_1 = data.frame(id = c(1,2), a = c(1,2))
file_2 = data.frame(id = c(1,2), b = c(3,4))
file_3 = data.frame(id = c(3,4), a = c(5,6))
Reduce(\(...) merge(..., all = T), mget(ls(pattern = "file")))
id a b
1 1 1 3
2 2 2 4
3 3 5 NA
4 4 6 NA
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/410876.html
標籤:
上一篇:HashMap<String,dynamic>dartflutter的記錄/列印串列
下一篇:未處理的例外:型別'_InternalLinkedHashMap<String,dynamic>'不是型別'HashMap<String,dynamic
