gen*_*ama 15 r dataframe data.table
如何在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
Run Code Online (Sandbox Code Playgroud)
gen*_*ama 13
我写了这个函数来完成那个任务.我称之为"写临时文件"或"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)
Run Code Online (Sandbox Code Playgroud)
如果你多次打开同一个对象,由于错误处理它仍然会工作,但它会有一个凌乱的临时名称.
wtf(df)
df$MoreData = pi
wtf(df)
Run Code Online (Sandbox Code Playgroud)