中华V语言的数据输入,二个用安德拉管理Excel文件的长足平台

<!DOCTYPE html>

既是理解了猎豹CS6语言的着力数据类型,那么哪些将不小的数据送入凯雷德语言实行拍卖呢?送入的数量又是怎么着在Enclave语言中开展仓库储存的吗?管理这一个多少的法子又有那多少个呢?上边我们一并来探究一下。

XLConnect:多少个用Evoque管理Excel文件的便捷平台

read.table(),read.csv(),read.delim()等函数能够直接读取EXCEl文件,但或多或少总会碰着一些难点。XLConnect函数包,是三个足以用中华V管理Excel文件的急忙平台。利用它能够读取或创建一个XLSX文件,并对文件进行数据管理,对文本内数据开展标识,以及可视化。

率先,数据输入最直接最直观的主意正是键盘输入,在上头几篇都早已讲到,利用c创立向量,利用matrix创设矩阵,利用data.frame创制数据框等,不过大家管理的数码往往非常多,键盘输入在面对如此小幅的多少时一望而知不具体,当然你能够费用数天来输入数据同至极候保险不出错除了那一个之外,并且待管理的形似都存款和储蓄在Excel,网页,数据库其余中介中,由此:怎么样大量无差错高功效地读取数据就改为QX56语言首先要消除的标题。

始建读取xlsl文件

require("XLConnect")

## Loading required package: XLConnect## Loading required package: XLConnectJars## XLConnect 0.2-11 by Mirai Solutions GmbH [aut],##   Martin Studer [cre],##   The Apache Software Foundation [ctb, cph] (Apache POI, Apache Commons##     Codec),##   Stephen Colebourne [ctb, cph] (Joda-Time Java library)## http://www.mirai-solutions.com ,## http://miraisolutions.wordpress.com

# 读取或创建一个XLSX文件,此步相当于建立一个连接xls <- loadWorkbook('C:/Users/ShangFR/Desktop/test.xlsx',create=TRUE) # 创建工作表createSheet(xls,name='namesheet')# 写入数据writeWorksheet(xls,iris,'namesheet',               startRow=5,startCol=5, # 数据出现的左上角位置               header=TRUE)# 存入硬盘,直到此步方才有文档生成saveWorkbook# 上面四个步骤是新建文档、新建工作表、写入数据、最后存盘。如果要写入数据的同时创建好区域名称,则在第三步有所不同。# 创建区域名createName(xls,name='nameregion',           formula='namesheet!$C$5', #区域的左上角单元格位置           overwrite=TRUE)# 写入数据writeNamedRegion(xls,iris,name='nameregion')# 读取文档则简单的多data <- readWorksheet(xls, 'namesheet',              startRow=1, startCol=1,              endRow=0,endCol=0, #取0表示自动判断              header=TRUE)

先是:借使本身攻读写代码,加载Lacrosse语言中自己自带的数额包cars等,加载的法子跟其他包同样,具体代码如下:

文件内数据符号、管理和可视化

> install.packages> library

一、创造汇率excel

#一、创建汇率excelrequire(XLConnect)require

## Loading required package: zoo## ## Attaching package: 'zoo'## ## The following objects are masked from 'package:base':## ##     as.Date, as.Date.numeric

require # >= 0.9.3

## Loading required package: ggplot2

curr = XLConnect::swissfranccurr = curr[order(curr$Date),]wbFilename = "swiss_franc.xlsx"wb = loadWorkbook(wbFilename, create = TRUE) # Create a new sheet named 'Swiss_Franc' sheet = "Swiss_Franc"createSheet(wb, name = sheet)# Create a new Excel name referring to the top left corner # of the sheet 'Swiss_Franc' - this name is going to hold # our currency datadataName = "currency"nameLocation = paste(sheet, "$A$1", sep = "!") createName(wb, name = dataName, formula = nameLocation) # Instruct XLConnect to only apply a data format for a cell   # but not to apply any other cell styling setStyleAction(wb, XLC$"STYLE_ACTION.DATA_FORMAT_ONLY") # Set the default format for numeric data to display   # four digits after the decimal pointsetDataFormatForType(wb, type = XLC$"DATA_TYPE.NUMERIC", format = "0.0000") # Write the currency data to the named region created above   # Note: the named region will be automatically redefined to encompass all   # written data writeNamedRegion(wb, data = curr, name = dataName, header = TRUE) # Save the workbook (this actually writes the file to disk)saveWorkbook#二、颜色标记-特殊值  # Load the workbook created above wb = loadWorkbook(wbFilename)  # Create a cell style for the header row csHeader = createCellStyle(wb, name = "header")setFillPattern(csHeader, fill = XLC$FILL.SOLID_FOREGROUND)setFillForegroundColor(csHeader, color = XLC$COLOR.GREY_25_PERCENT)  # Create a date cell style with a custom format for the Date columncsDate = createCellStyle(wb, name = "date")setDataFormat(csDate, format = "yyyy-mm-dd")  # Create a highlighting cell stylecsHlight = createCellStyle(wb, name = "highlight")setFillPattern(csHlight, fill = XLC$FILL.SOLID_FOREGROUND) setFillForegroundColor(csHlight, color = XLC$COLOR.CORNFLOWER_BLUE)  # Apply header cell style to the header rowsetCellStyle(wb, sheet = sheet, row = 1,                   col = seq(length.out = ncol,                   cellstyle = csHeader)  # Index for all rows except header rowallRows = seq(length = nrow + 1  # Apply date cell style to the Date columnsetCellStyle(wb, sheet = sheet, row = allRows, col = 1,cellstyle = csDate)  # Set column width such that the full date column is visiblesetColumnWidth(wb, sheet = sheet, column = 1, width = 2800) # Check if there was a change of more than 2% compared    # to the previous day (per currency)idx = rollapply(curr[, -1], width = 2,                     FUN = function abs(x[2] / x[1] - 1),                     by.column = TRUE) > 0.02idx = rbind(rep(FALSE, ncol, idx)widx = lapply(as.data.frame, which)  # Apply highlighting cell stylefor(i in seq(along = widx)) {     if(length(widx[[i]]) > 0) {        setCellStyle(wb, sheet = sheet, row = widx[[i]] + 1, col = i + 1,cellstyle = csHlight)     }        } saveWorkbook #三、添加汇率趋势图  wb = loadWorkbook(wbFilename)  # Stack currencies into a currency variable (for use with ggplot2 below)    currencies = names[-1]  gcurr = reshape(curr, varying = currencies, direction = "long",                    v.names = "Value", times = currencies, timevar = "Currency")  # Create a png graph showing the currencies in the context    # of the Swiss Franc    png(filename = "swiss_franc.png", width = 800, height = 600)  p = ggplot(gcurr, aes(Date, Value, colour = Currency)) +    geom_line() + stat_smooth(method = "loess") +    scale_y_continuous("Exchange Rate CHF/CUR") +    labs(title = paste0("CHF vs ", paste(currencies, collapse = ", ")),           x = "") +    theme(axis.title.y = element_text(size = 10, angle = 90, vjust = 0.3))  print  dev.off()

## png ##   2

  p

88bifa必发唯一官网 1

  # Define where the image should be placed via a named region;    # let's put the image two columns left to the data starting    # in the 5th row    createName(wb, name = "graph",                 formula = paste(sheet, idx2cref(c(5, ncol + 2)), sep = "!"))  # Put the image created above at the corresponding location    addImage(wb, filename = "swiss_franc.png", name = "graph",               originalSize = TRUE)  saveWorkbook

XLConnect的扶持文书档案内有详细介绍,感兴趣的可径直参考。

第二:读取外界数据一般用read.***,***表示要读取的文件类型,下边详细分解了每体系型的文件的读取:

报告与提出

  • 作者:ShangFR
  • 邮箱:shangfr@foxmail.com
read.table(file, header = FALSE, sep = "", quote = "\"'",           dec = ".", numerals = c("allow.loss", "warn.loss", "no.loss"),           row.names, col.names, as.is = !stringsAsFactors,           na.strings = "NA", colClasses = NA, nrows = -1,           skip = 0, check.names = TRUE, fill = !blank.lines.skip,           strip.white = FALSE, blank.lines.skip = TRUE,           comment.char = "#",           allowEscapes = FALSE, flush = FALSE,           stringsAsFactors = default.stringsAsFactors(),           fileEncoding = "", encoding = "unknown", text, skipNul = FALSE)read.csv(file, header = TRUE, sep = ",", quote = "\"",         dec = ".", fill = TRUE, comment.char = "", ...)read.csv2(file, header = TRUE, sep = ";", quote = "\"",          dec = ",", fill = TRUE, comment.char = "", ...)read.delim(file, header = TRUE, sep = "\t", quote = "\"",           dec = ".", fill = TRUE, comment.char = "", ...)read.delim2(file, header = TRUE, sep = "\t", quote = "\"",            dec = ",", fill = TRUE, comment.char = "", ...)

其中:

参数file:代表要读去的文件名以及文件路线,固然当前专门的工作路线正是亟需读取的文书的贮存路线,那么能够直接写文件名,记得要用双引号括起来。那么什么样设置工作路线呢?首先大家查阅当前的干活路径用getwd函数,设置专门的学业门路的话用setwd函数,注意,在安装专门的学业路径时,须求把门路中具有的
“\” 改成 “\\”。具体操作如下代码:

> getwd()    #查看当前工作路径[1] "E:/赵志博/R"> setwd #错误的设置方式Error: '\? is an unrecognized escape in character string starting ""E:\?> setwd("E:\\赵志博") #正确的设置方式> getwd()    #查看设置后的工作路径[1] "E:/赵志博"

当职业路径设置达成后,便足以一直读取工作门路里面包车型客车文本而无需Gavin件的仓库储存地方。如代码所示,当前工作路线为”E:/赵志博”,在该路径下成立了文本“123.txt”,可以从来读取文件,不过在“D:/”创立了新的文本“456.txt”,便不可能向来读取,须要增加全体的文件路径,路线同样要求将”\”
改成 “\\”。

 mydata <- read.table("123.txt",sep = ',')> mydata  V1 V2 V31  1  2  32  4  5  63  7  8  9> mydataD <- read.table("456.txt",sep = ',')Error in file(file, "rt") : cannot open the connectionIn addition: Warning message:In file(file, "rt") : cannot open file '456.txt': No such file or directory> mydataD <- read.table("D:\\456.txt",sep = ',')> mydataD  V1 V2 V31  1  2  32  4  5  63  7  8  9

老是都要设置路线,对有个别场所来讲未免太过困苦,因而Koleos提供了一种能够一向采纳文件地方的函数,read.***88bifa必发唯一官网 ,(file.choose,比方读取txt数据:

mydatachoose <- read.table(file.choose #自由选取数据来读取,但是file.choose的参数好像没有

参数header:主要规定供给读取的文本是或不是友善已经设置了列名,暗中同意值为FALSE。那么些需求解释一下:上节大家已经讲过data.frame类型,那么read.***的重返值也是数量框类型,自然是按列填充的数码框格式,由此列名就展现尤为重大,也就是Excel的表底部分,行号系统会基于1~N的次第排好,当然也足以修改。

参数sep:重要规定须要读取的文本中,种种字符的划分格局,一般有空格分割,逗号分割等,明显了细分格局,技巧担保将数据读取为和睦想要的旗帜。

广泛用的参数就是这么些,其余的法规都差十分的少,假使有须求活动学习。

1.txt文件:mydata <- read.table

2.Excel格式数据:mydata <-
read.xlsx,在选用这些函数从前,必要先安装xlsx包,安装格局跟任何包的设置方式一致。一般的话,读取xlsx文件速度极慢,常常将Excel文件保留为csv格式,然后再张开读取
mydata <- read.csv

3.XML数码:读取XML数据前先要载入XML包,然后使用 mydata <-
xmlRoot(xmlTreeParse(“***.xml”))来读取

关于数据的读取就先介绍到此处,其余有效的着的再独自学习。