16

如何在 Excel 中快速打开小型 R 表/矢量对象?

例如,假设您有以下三个要在 Excel 中查看的对象:

## A data frame with commas and quotes
df = data.frame(
  area = unname(state.x77[,'Area']),
  frost = unname(state.x77[,'Frost']),
  comments = "Ok for a visit, but don't want to live there",
  challengeComments = c('"', '""'))
row.names(df) = state.name
df = df[1:10, ]
df['California', 'comments'] = "Would like to live here"

## A Matrix
mat = matrix(rnorm(100), 10)

## A Vector
v = 1:10
4

10 回答 10

14

我写了这个函数来完成这个任务。我称之为“写临时文件”或“wtf”。如果您有与 Excel 关联的 csv 文件,它仅适用于 Windows。

您可以查看 PBSmodelling::openFile 中的代码,了解如何将其应用于不同的操作系统。

wtf = function (x) {
  tempFilePath = paste(tempfile(), ".csv")
  tempPath = dirname(tempFilePath)
  preferredFile = paste(deparse(substitute(x)), ".csv", sep = "")
  preferredFilePath = file.path(tempPath, preferredFile)

  if(length(dim(x))>2){
    stop('Too many dimensions')
  }
  if(is.null(dim(x))){
    x = as.data.frame(x)
  }
  if (is.null(rownames(x))) {
    tmp = 1:nrow(x)
  }else {
    tmp = rownames(x)
  }
  rownames(x) = NULL
  x = data.frame(RowLabels = tmp, x)
  WriteAttempt = try(
    write.table(x, file=preferredFilePath, quote=TRUE, sep=",", na="",
                row.names=FALSE, qmethod="double"),
    silent = TRUE)
  if ("try-error" %in% class(WriteAttempt)) {
    write.table(x, file=tempFilePath, , quote=TRUE, sep=",", na="",
                row.names=FALSE, qmethod="double")
    shell.exec(tempFilePath)
  } else {
    shell.exec(preferredFilePath)
  }
}


wtf(df)
wtf(mat)
wtf(v)

如果您多次打开同一个对象,由于错误处理,它仍然可以工作,但它会有一个混乱的临时名称。

wtf(df)
df$MoreData = pi
wtf(df)
于 2012-08-28T18:00:15.687 回答
3

我编写了一个函数来在 Libre Office Calc 或 Excel 中打开文件。详情请看这里

view <- function(data, autofilter=TRUE) {
    # data: data frame
    # autofilter: whether to apply a filter to make sorting and filtering easier
    open_command <- switch(Sys.info()[['sysname']],
                           Windows= 'open',
                           Linux  = 'xdg-open',
                           Darwin = 'open')
    require(XLConnect)
    temp_file <- paste0(tempfile(), '.xlsx')
    wb <- loadWorkbook(temp_file, create = TRUE)
    createSheet(wb, name = "temp")
    writeWorksheet(wb, data, sheet = "temp", startRow = 1, startCol = 1)
    if (autofilter) setAutoFilter(wb, 'temp', aref('A1', dim(data)))
    saveWorkbook(wb, )
    system(paste(open_command, temp_file))
}
于 2012-10-18T07:01:03.350 回答
2

I wanted something that mimicked View() but in Excel, not in the internal view of RStudio. Learned little bits from numerous posts above. Eventually came to a pretty simple little bit of code that....so far... seems to do the trick for me.
Just want to quickly view it, but in Excel. If I decide I want to save the file, I can handle that within Excel. Otherwise it just automatically create a temp file in the default temp directory for that session of R. It's setup to act on the .Last.value of the R session as a default, or you pipe in an object that can be coerced to a data frame

I just have it defined in my R profile so its always available. Might make more sens to name it ViewExt for "View External" so as to not link it directly to Excel but whatever program of choice the user has set in Windows to be the default editor for a .csv file. But thats what I use so that's what I named it

    ViewExcel <- function(df = .Last.value, file = tempfile(fileext = ".csv")) {
       df <- try(as.data.frame(df))
       stopifnot(is.data.frame(df))
       utils::write.csv(df, file = file)
       base::shell.exec(file)
    }

    #Examples
    mtcars
    ViewExcel()
    mtcars %>% ViewExcel()
    ViewExcel(mtcars)
于 2019-11-21T14:43:36.063 回答
1

对不起无耻的广告......你可以试试我的包http://cran.r-project.org/web/packages/excel.link/index.html 它看起来像:

library(excel.link)
xlrc[a1]=df

它依赖于 Omegahat RDCOMClient 包,因此有必要从源代码安装它:

install.packages("RDCOMClient", repos = "http://www.omegahat.org/R")
install.packages("excel.link", repos = "http://cran.at.r-project.org",type="source")
于 2012-08-28T22:01:17.567 回答
1

我经常使用它来将数据表粘贴到 Excel 中:

write.table(x, "clipboard", row.names=F, sep='\t')

并将 Excel 中的(子)表复制到 R 中,执行以下操作(假设表有标题行):

read.csv('clipboard', sep='\t')
于 2016-02-11T03:51:30.523 回答
1

使用view_in_xlviewxl 包中的函数。这相当于在 RStudio 中使用 F4 键盘快捷键。

viewxl:::view_in_xl(x)
于 2022-01-03T18:02:55.693 回答
1

geneorama的解决方案很棒,但是使用write.table会很慢。您可以将其更改fwritedata.table 包

这个解决方案有用的主要原因(至少对我来说)是因为大数据帧View糟糕。我geneorama用 15600 obs 的数据框测试了 的解决方案。通过 1270 个变量,它在 16 秒后打开。fwrite0.6秒后打开的版本!

这是修改后的功能:

wtf = function (x) {
  tempFilePath = paste(tempfile(), ".csv")
  tempPath = dirname(tempFilePath)
  preferredFile = paste(deparse(substitute(x)), ".csv", sep = "")
  preferredFilePath = file.path(tempPath, preferredFile)

  if(length(dim(x))>2){
    stop('Too many dimensions')
  }
  if(is.null(dim(x))){
    x = as.data.frame(x)
  }
  if (is.null(rownames(x))) {
    tmp = 1:nrow(x)
  }else {
    tmp = rownames(x)
  }
  rownames(x) = NULL
  x = data.frame(RowLabels = tmp, x)
  WriteAttempt = try(
    data.table::fwrite(x, file=preferredFilePath, quote=TRUE),
    silent = TRUE)
  if ("try-error" %in% class(WriteAttempt)) {
    data.table::fwrite(x, file=tempFilePath, quote=TRUE)
    shell.exec(tempFilePath)
  } else {
    shell.exec(preferredFilePath)
  }
}
于 2018-06-01T03:22:05.403 回答
0

我为windows写了一个函数。但可能它也适用于其他操作系统。

它在 C:\Users\...\Documents\Rview 中创建临时文件,并使用 browseURL() 打开它们。您最多可以同时打开 99 个文件。您可以通过参数“名称”轻松选择应显示的暗名称。该函数将在 col/rownames 的 +,-,= 之前添加 ',以便在 Excel 中正确显示。

我个人更喜欢使用 Sys.getenv("TMP") 而不是使用 tempfile() 的解决方案,因为 tempfile() 会在一段时间后弄乱您的临时文件夹。

有关详细信息,请参阅代码顶部的参数描述。

# This function creates a CSV file from a data.frame/matrix and opens it with the default CSV-opening-program
# of the computer.
#
# x = data.frame/matrix
# names = dimnames to be saved in the file. "col"=colnames, "rowcol"=rownames&colnames, "row"=rownames, "no"=no dimnames
# nrows = maximum number of rows    to be saved (for higher speed with large datasets)
#         if n=-1, all rows will be displayed.-> see also the help for read.table()
# ncols = maximum number of columns to be saved (for higher speed with large datasets)
# folder = directory, where the temporary file should be saved.
#          If NULL an accessible folder in C:/Users/.../Documents will be created automatically.
# quote = should quotes be written into the csv File? -> see also the help for write.table()
# na = how should NA values be displayed in the csv File? -> see also the help for write.table()
# openfolder = Should the folder with all temporary files be opened after having created the file?

view <- function(x, names=c("col","rowcol","row","no"), nrows=10000, ncols=1000, folder=NULL, quote=FALSE, na="NA", openfolder=FALSE, ...){

  names <- match.arg(names)
  if(is.null(dim(x))) {
    x <- as.matrix(x)
  }
  if(is.null(colnames(x))) colnames(x) <- paste0("V",1:ncol(x))

  if(nrows<0) nrows <- nrow(x)
  if(ncols<0) ncols <- ncol(x)
  # Shrink data.frame such that it can be saved & viewed faster.
  nrows <- min(nrow(x), nrows)
  if(nrows!=nrow(x)) x <- x[1:nrows,,drop=FALSE]
  ncols <- min(ncol(x), ncols)
  if(ncols!=ncol(x)) x <- x[,1:ncols,drop=FALSE]


  # Define paths
  # If is.null(folder), wird ein temporaerer Ordner im Windows-Dateisystem angelegt.
  if(is.null(folder)) {
    folder <- paste0(Sys.getenv("TMP"), "\\Rview")
    suppressWarnings( dir.create(folder) )
  }  

  # Wenn am Schluss des Pfades kein "/" angefuegt wurde, wird dies gemacht:
  if( !substr(folder,nchar(folder),nchar(folder))%in%c("/","\\") ) folder <- paste0(folder, "\\")
  pfad0 <- folder
  name <- "Rview_tmp"
  nr <- "01"
  csv <- ".csv"

  # Check if there are existing files in the folder
  fil <- list.files(pfad0)
  # If there are no files in the folder, use the default save path.
  if(length(fil)==0){
    pfad1 <- paste0(pfad0, name, nr, csv)
  } else {
    # Remove all files in the folder (if possible)
    fil <- paste0(pfad0, fil)
    suppressWarnings( try( file.remove( fil )  , silent=TRUE) )
    fil <- list.files(pfad0)
    # If there are no files anymore use the default save path.
    if( length(fil)==0 ) {
      pfad1 <- paste0(pfad0, name, nr, csv)
    } else {
      # If there are sill files, read out the number of the newest file (with the highest number)
      ncharfil <- nchar(fil)
      mx <- max( as.numeric( substr(fil,ncharfil-5,ncharfil-4) ) )
      # Add 1 to the number of the file
      mxpl1 <- as.character( mx+1 )
      if(nchar(mxpl1)==1) mxpl1 <- paste0("0",mxpl1)
      # Create a new path
      pfad1 <- paste0(pfad0, name, mxpl1, csv)
    }
  }

  # Rownames und colnames, die mit +, - oder = anfangen, mit ' am Anfang versehen, dass es von Excel richtig dargestellt wird
  rn1 <- rownames(x)
  cn1 <- colnames(x)
  ind <- substr(rn1,1,1)%in%c("+","-","=")
  if(any(ind)) rownames(x)[ind] <- paste0(" ",rn1[ind])
  ind <- substr(cn1,1,1)%in%c("+","-","=")
  if(any(ind)) colnames(x)[ind] <- paste0(" ",cn1[ind])

  # Write CSV file & open.
  if(names=="row") {
    # If the first cell of the file is named "ID" Microsoft Excel warns that a SYLK file is opened. Therefore it is renamed.
    if(rownames(x)[1]=="ID") rownames(x)[1] <- "lD"
    write.table(x, file=pfad1, sep = ";", col.names=FALSE, row.names=TRUE, quote=quote, na=na, ...)
  } else if (names=="col") {
    # If the first cell of the file is named "ID" Microsoft Excel warns that a SYLK file is opened. Therefore it is renamed.
    if(colnames(x)[1]=="ID") colnames(x)[1] <- "lD"
    write.table(x, file=pfad1, sep = ";", col.names=TRUE, row.names=FALSE, quote=quote, na=na, ...)
  } else if (names=="rowcol") {
    write.table(x, file=pfad1, sep = ";", col.names=NA)                    # Colnames & Rownames
  } else {
    write.table(x, file=pfad1, sep = ";", col.names=FALSE, row.names=FALSE, quote=quote, na=na, ...)
  }

  browseURL(pfad1)
  if(openfolder) {
    Sys.sleep(1)
    browseURL(folder)
  }
}
于 2016-02-26T15:52:43.153 回答
0

不完全回答这个问题,因为这不仅限于 Excel,但这里有一个简单的函数(受其他一些答案的启发),它从对象创建一个临时 csv 文件并将其路径复制到剪贴板(使用 package clipr)。

这允许通过简单地键入所选应用程序的名称并将剪贴板的内容粘贴到命令行中来快速可视化任何应用程序中的对象(例如sc-im 、Libreoffice calc、Excel、Gnumeric 等)。

ext <- function(data) {
    file_name <- tempfile(fileext = ".csv")
    file <- write.csv(data, file_name)
    clipr::write_clip(paste(file_name))
}

我最初使用这个是因为我很难sc-im从 R 中打开一个文件system(),但最后,我发现能够选择我想用来可视化临时文件的应用程序非常方便:取决于我想探索的对象,一个或另一个应用程序可能更合适。

于 2019-05-16T20:57:53.153 回答
-2

write.csv(x, "clipboard")在excel中使用和粘贴。

于 2012-08-28T19:48:10.183 回答