Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (50.2k points)
edited by

I am importing the data from multiple excel files using the readxl package and I made a function in my script so that I can only import specific sheets that I need:

read_excel_sheets <- function(excelDoc) {

     sheets <- readxl::excel_sheets(excelDoc)

     sheets <- sheets[4:6]

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

     return(x)

}

#load files in folder

rawfiles <- list.files()

IMPORT <- lapply(rawfiles, FUN = read_excel_sheets)

After importing all the files from my folder into my script, IMPORT becomes a list[10] that contains a list[3] inside of it, basically lists inside of a list.

I have tried working with just one excel file and using unlist() to see if I can get my sheets out of the lists of list but that did not work.

Test <- read_excel_sheets("Hop_L_Trial1.xlsx")

Test_Test <- unlist(Test)

I've also tried:

rawfiles <- list.files()

IMPORT <- lapply(rawfiles,

                FUN = read_excel_sheets) 

Test_3 <- rbindlist(IMPORT) 

How can I join my data into one data table?

1 Answer

0 votes
by (107k points)

For that you can use bind_rows() from the dplyr package in R programming:

x <- list(tibble(x=runif(5)),  tibble(x=runif(5)))

y <- list(tibble(x=runif(5)),  tibble(x=runif(5)))

z = list(x, y)

ans <- bind_rows(z)

ans

A tibble: 20 x 1

        x

    <dbl>

 1 0.746 

 2 0.0669

 3 0.612 

 4 0.0702

 5 0.990 

 6 0.301 

 7 0.177 

 8 0.799 

 9 0.242 

10 0.741 

11 0.651 

12 0.113 

13 0.927 

14 0.506 

15 0.477 

16 0.922 

17 0.217 

18 0.566 

19 0.539 

20 0.327 

You can use bind_rows(..., .id="Sheet") if you need to track which element of the list each row came from originally.

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...