有沒有辦法在R中獲取有關多個CSV檔案的行數和列數的資訊并將其保存在CSV檔案中?這是我的 R 代碼:
#Library
if (!require("tidyverse")) install.packages("tidyverse")
if (!require("fs")) install.packages("fs")
#Mentioning Files Location
file_paths <- fs::dir_ls("C:\\Users\\Desktop\\FileCount\\Test")
file_paths[[2]]
#Reading Multiple CSV Files
file_paths %>%
map(function(path)
{
read_csv(path,col_names = FALSE)
})
#Counting Number of Rows
lapply(X = file_paths, FUN = function(x) {
length(count.fields(x))
})
#Counting Number of Columns
lapply(X = file_paths, FUN = function(x) {
length(ncol(x))
})
#Saving CSV File
write.csv(file_paths,"C:\\Users\\Desktop\\FileCount\\Test\\FileName.csv", row.names = FALSE)
有幾件事不起作用:
- 多個 CSV 檔案的列數
- 當我保存檔案時,我想保存檔案名、行數和列數。見附圖。
輸出結果如下:

附上一些用于測驗的 CSV 檔案:這里
任何幫助表示贊賞。
uj5u.com熱心網友回復:
歡迎來到 SO!使用tidyverseand data.table,這是一種方法:
注意:所有 .csv 檔案都在我的TestStack目錄中,但您可以使用自己的目錄 ( C:/Users/Desktop/FileCount/Test)更改它。
代碼:
library(tidyverse)
csv.file <- list.files("TestStack") # Directory with your .csv files
data.frame.output <- data.frame(number_of_cols = NA,
number_of_rows = NA,
name_of_csv = NA) #The df to be written
MyF <- function(x){
csv.read.file <- data.table::fread(
paste("TestStack", x, sep = "/")
)
number.of.cols <- ncol(csv.read.file)
number.of.rows <- nrow(csv.read.file)
data.frame.output <<- add_row(data.frame.output,
number_of_cols = number.of.cols,
number_of_rows = number.of.rows,
name_of_csv = str_remove_all(x,".csv")) %>%
filter(!is.na(name_of_csv))
}
map(csv.file, MyF)
輸出:
number_of_cols number_of_rows name_of_csv
1 3 2150 CH_com
2 2 34968 epci_com_20
3 3 732 g1g4
4 7 161905 RP
我有這個輸出是因為我TestStack有 4 個檔案名為 CH_com.csv、epci_com_20.csv、...
然后,您可以根據需要將物件寫入data.frame.output.csv:data.table::fwrite(data.frame.output, file = "Output.csv")
uj5u.com熱心網友回復:
files_map <- "test"
files <- list.files(files_map)
library(data.table)
output <- data.table::rbindlist(
lapply(files, function(file) {
dt <- data.table::fread(paste(files_map, file, sep = "/"))
list("number_of_cols" = ncol(dt), "number_of_rows" = nrow(dt), "name_of_csv" = file)
})
)
data.table::fwrite(output, file = "Filename.csv")
或者使用 map 和單獨的函式來完成任務,但不首先使用空表并使用全域分配更新它。我看到這種情況在應用函式上經常發生,而根本不需要。
myF <- function(file) {
dt <- data.table::fread(paste(files_map, file, sep = "/"))
data.frame("number_of_cols" = ncol(dt), "number_of_rows" = nrow(dt), "name_of_csv" = file)
}
output <- do.call(rbind, map(files, myF))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/369335.html
上一篇:使用points()繪制函式
