Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can R identify if the Excel file has commented cells?

Tags:

r

excel

I have an excel sheet .xlsx, which have some commented cells in it. After importing it in R, is there any way by which R can identify the commented cells?

Because I have to use some if else conditions only to the commented cells.

like image 913
Suvodip Ghosh Avatar asked Mar 14 '18 20:03

Suvodip Ghosh


People also ask

How do I get a list of comments in Excel?

To display all comments in the worksheet, go to the Review tab > Show all Comments. To move or resize any overlapping comments, right-click and select Edit Comment, and the border of the comment box will display sizing handles.

Can R read Excel files?

The xlsx package, a java-based solution, is one of the powerful R packages to read, write and format Excel files.


1 Answers

Let's say we have this file, test.xlsx: enter image description here

Using openxlsx we can read the workbook as a dataframe object to extract only data:

library(openxlsx)

# read the data
df1 <- read.xlsx("test.xlsx")
df1
#    1  no
# 1  2 yes
# 2  3  no
# 3  5  no
# 4 10 yes

If we need to extract comments, we need to read as workbook object:

# read as workbook object
wb <- loadWorkbook("test.xlsx")

Check the structure of the object to see where the cell reference is stored:

str(wb$comments)
# List of 3
# $ :List of 2
# ..$ :List of 5
# .. ..$ ref       : chr "B2"
# ...
# ... etc

Then subset, loop through sheets, and subset cell reference with comments:

lapply(wb$comments, function(sheet)
  sapply(sheet, "[[", "ref"))
# [[1]]
# [1] "B2" "B5"
# 
# [[2]]
# list()
# 
# [[3]]
# list()

This means there are 3 sheets, 1st sheet has 2 comments at B2 and B5, other 2 sheets are blank.

like image 176
zx8754 Avatar answered Sep 30 '22 04:09

zx8754