Read A Block of Spreadsheet with R
[This article was first published on Yet Another Blog in Statistical Computing » S+/R, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
In R, there are two ways to read a block of the spreadsheet, e.g. xlsx file, as the one shown below.
The xlsx package provides the most intuitive interface with readColumns() function by explicitly defining the starting and the ending columns and rows.
library(xlsx) file <- loadWorkbook("C:\Documents and Settings\Administrator\Desktop\test.xlsx") df1 <- readColumns(getSheets(file)[[1]], startColumn = 3, endColumn = 5, startRow = 5, endRow = 8, header = T) df1 # X Y Z # 1 1 A 2015-01-01 # 2 2 B 2015-02-01 # 3 3 C 2015-03-01
However, if we can define a named range for the block in the excel, the XLConnect package might be more convenient. In the example below, we first defined a range named as “block” within the spreadsheet and then called this named range with readNamedRegionFromFile() function without the necessity of specifying rows and columns.
library(XLConnect) df2 <- readNamedRegionFromFile("C:\Documents and Settings\Administrator\Desktop\test.xlsx", "block") df2 # X Y Z # 1 1 A 2015-01-01 # 2 2 B 2015-02-01 # 3 3 C 2015-03-01
To leave a comment for the author, please follow the link and comment on their blog: Yet Another Blog in Statistical Computing » S+/R.
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.