在R中:如何对多个文件执行str()

时间:2014-10-15 22:01:16

标签: r rstudio

如何在R中同时在工作区中加载的所有这些文件中执行str()函数?我只想将这些信息导出,但是在类似批处理的过程中,导出到.csv文件。我有超过100个,并希望将一个工作区与另一个工作区进行比较,以帮助找到数据结构中的不协调并避免不匹配。

我通过UCLA's 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以防有人可能知道自动导出该表的方法?我无法找到办法。 enter image description here

提前致谢。

2 个答案:

答案 0 :(得分:2)

我实际上已经为此编写了一个函数。我还问了a question about it, and dealing with promise objects with the function。那篇文章可能对你有用。

最后一栏的问题是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环境的屏幕截图。

enter image description here

答案 1 :(得分:0)

我会写一个函数,如下所示。然后循环遍历该函数,因此您基本上编写单个数据集的代码

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 )