0 votes
1 view
in R Programming by (48.5k points)
edited by

Basically I am having different sheets from excel file and I want to import each and every sheet to RStudio and to add the sheet name in every data frame as a variable, as I want to make one data frame but I need to know from which sheet they are from?


read_excel_allsheets <- function("datafile", tibble = false) {

sheets <- readxl::excel_sheets("datafile")

x <- lapply(sheets, function(X) readxl::read_excel("datafile", sheet = X))

if(!tibble) x <- lapply(x, as.data.frame)

names(x) <- sheets



#Integra las hojas en una sola

datos = x[[1]]

for(i in 2:3){

datoscompletos = rbind.data.frame(datos,x[[i]])

datos = datoscompletos

1 Answer

0 votes
by (104k points)

In R programming you can get your desired output with the help of lapply function. Kindly refer the following code:

sheets <- readxl::excel_sheets("datafile")

all_data <- do.call(rbind, lapply(sheets, function(X) 

        transform(readxl::read_excel("datafile", sheet = X), sheetname = X)))

You can do the same in tidyverse also, refer the below code:

purrr::map_df(sheets, ~dplyr::mutate(readxl::read_excel("datafile", sheet = .x), 

                       sheetname = .x))

Welcome to Intellipaat Community. Get your technical queries answered by top developers !