[英]How to extract information and perform the same operation on multiple similar files in R?
[英]In R: How to perform a str() on multiple files
如何在R中同時對工作區中加載的所有這些文件執行str()
函數? 我只是想以類似批處理的方式將這些信息導出到.csv文件。 我有100多個,並且想要將一個工作空間與另一個工作空間進行比較,以幫助查找數據結構中的不一致性並避免不匹配。
我非常痛苦地接近通過UCLA的R Code Fragment解決方案,但是,他們沒有包含有關如何形成遍歷文件的read.dta函數的說明。 這是我需要幫助的部分。
到目前為止,我有:
#Define the file path
f <- file.path("C:/User/Datastore/RData")
#List the files in the path
fn <- list.files(f)
#loop through file list, return str() of each .RData file
#write to .csv file with 4 columns (file name, length, size, value)
編輯
這是我所追求的示例(RStudio的視圖-它僅列出了所有RData文件的名稱,類型,長度,大小和值)。 我想基本上復制此視圖,但將其導出到.csv。 我將標簽添加到RStudio中,以防有人知道自動導出該表的方法嗎? 我找不到辦法。
提前致謝。
實際上,我已經為此編寫了一個函數。 我還問了一個問題,並使用函數處理promise對象 。 該帖子可能對您有用。
最后一列的問題是str
不能做任何事情,只能打印對象的簡短描述,因此我無法使用它(但是最近的編輯已對其進行了更改)。 此更新的函數提供了與RStudio表類似的值的描述。 數據幀和列表比較棘手,因為它們的str
輸出超過一行。 這應該很好。
objInfo <- function(env = globalenv())
{
obj <- mget(ls(env), env)
out <- lapply(obj, function(x) {
vals1 <- c(
Type = toString(class(x)),
Length = length(x),
Size = object.size(x)
)
val2 <- gsub("|^\\s+|'data.frame':\t", "", capture.output(str(x))[1])
if(grepl("environment", val2)) val2 <- "Environment"
c(vals1, Value = val2)
})
out <- do.call(rbind, out)
rownames(out) <- seq_len(nrow(out))
noquote(cbind(Name = names(obj), out))
}
然后我們可以在一些對象上進行測試。
x <- 1:10
y <- letters[1:5]
e <- globalenv()
df <- data.frame(x = 1, y = "a")
m <- matrix(1:6)
l <- as.list(1:5)
objInfo()
# Name Type Length Size Value
# 1 df data.frame 2 1208 1 obs. of 2 variables
# 2 e environment 11 56 Environment
# 3 l list 5 328 List of 5
# 4 m matrix 6 232 int [1:6, 1] 1 2 3 4 5 6
# 5 objInfo function 1 24408 function (env = globalenv())
# 6 x integer 10 88 int [1:10] 1 2 3 4 5 6 7 8 9 10
# 7 y character 5 328 chr [1:5] a b c d e
我猜這很接近。 這是RStudio中環境的屏幕截圖。
我將編寫一個函數,如下所示。 然后遍歷該函數,因此您基本上可以為單個數據集編寫代碼
library(foreign)
giveSingleDataset <- function( oneFile ) {
#Read .dta file
df <- read.dta( oneFile )
#Give e.g. structure
s <- ls.str(df)
#Return what you want
return(s)
}
#Actually call the function
result <- lapply( fn, giveSingleDataset )
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.