在Excel中快速查看R data.frame,vector或data.table [英] Quickly view an R data.frame, vector, or data.table in Excel
问题描述
如何在Excel中快速打开小的R表/向量对象?
How do you quickly open small R table / vector objects in Excel?
例如,假设您想在Excel中查看以下三个对象: / p>
For example suppose you have the following three objects that you want to view in 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
推荐答案
我写了这个函数来完成这个任务,我称之为写临时文件或wtf它只适用于windows如果你有csv文件与Excel相关联。
I wrote this function to accomplish that task. I call it "write temp file", or "wtf". It only works on windows if you have csv files associated with Excel.
您可以查看PBSmodelling :: openFile中的代码,了解如何将它应用于不同的操作系统。
You might look at the code in PBSmodelling::openFile to see how to adopt it to different operating systems.
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)
如果你多次打开同一个对象,它仍然会工作,由于错误处理,但它会有一个凌乱的临时名称。
if you open the same object multiple times, it will still work thanks to the error handling, but it will have a messy temp name.
wtf(df)
df$MoreData = pi
wtf(df)
这篇关于在Excel中快速查看R data.frame,vector或data.table的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!