Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you change single entries in an excel file with R and not the entire data sheet?

I have an excel file with some data in it. I want to use R to run some statistics on said sheet and then save some values into different columns in the original Excel Sheet. Is there any way to do this without always "overwriting" the whole excel file?

My_data <- read_xlsx("MeasurementData.xlsx", sheet = "Data_Overview")
data$Column1[1] = "result"
write.xlsx(My_data, file="MeasurementData.xlsx", sheetname="Data_Overview" )

So what I am attempting to do with this code is opening my xlsx file, changing one entry of it to "result" and then rewriting the whole slightly changed dataframe into the xlsx file. However what I want is to not rewrite the entire file but only overwrite/replace the changed entries.

Is there any way to do this? Thanks!

like image 246
ikempf Avatar asked Nov 19 '19 14:11

ikempf


People also ask

How do I allow certain cells to edit in Excel?

On the Review tab, click Protect Sheet. In the Allow all users of this worksheet to list, choose the elements that you want users to be able to change. Moving the pointer to cells for which the Locked check box is selected on the Protection tab of the Format Cells dialog box.

How do you isolate certain data in Excel?

Place your mouse pointer on “Highlight Cell Rules” and review the list of options. Choose the one most appropriate for your purpose and click on it to open the rules dialog box. For example, select “equal to” to isolate a specific value or “duplicate values” to find duplicate data entries.

How do you write to an existing Excel file in R?

Write Data to an Excel File To write to an existing file, use write. xlsx() method and pass the data in the form of matrix or data frame. Notice that the write. xlsx() function prepends each row with a row name by default.


1 Answers

I would suggest that you use the openxlsx package instead, where you can update specific cells in a specific sheet without corrupting the other sheets in the file.

Here is an example:

install.packages("openxlsx")
library(openxlsx)
wb <- loadWorkbook("https://github.com/awalker89/openxlsx/files/744103/template.xlsx")

writeData(wb, sheet = "Iris Data", x = head(iris, 20))
saveWorkbook(wb, "populated_template.xlsx")
openXL("populated_template.xlsx")

As you will see, formatting is untouched and there is another sheet in the file that contains a plot for the populated data is also intact.

You can set x to a single value (as in your example) and set the position as you like (using startCol and startRow.

Hope you find it useful.

like image 115
Taher A. Ghaleb Avatar answered Oct 13 '22 00:10

Taher A. Ghaleb