Search code examples
rexcelreadrreadxl

deleting a column while loading excel into R


I have an Excel that I need to load into R.

Excel have columns for example - A,B,C,D,E I am trying to load it and arrange the excel in the below way-

df1 <- read_excel("abc.xlsx") %>% 
       arrange(A)  

The above code would load the excel with columns A,B,C,D,E and arrange it on basis of A Asc.

Is there any way I can delete few columns like D,E or C,E or B,C while loading that excel itself?


Solution

  • Yes, it is possible to only read a range of columns. In this case i read only the first 3 columns (1:3)

    df1 <- read_excel("abc.xlsx", range = cell_cols(1:3)) %>% 
           arrange(A) 
    

    Because you changed your question now an edit:

    If you want to read random cells like A:C and F:G you can also use cell_cols. You would then need 2 lines of code and then merge it together. As i understanbd you want to provide the Letters, so this is possible:

    df1 <- read_excel("abc.xlsx", range = cell_cols("A:C"))
    df2 <- read_excel("abc.xlsx", range = cell_cols("F:G"))
    df <- cbind(df1, df2)
    

    At the end, read_excel is not providing a solution for your problem. I think you would need to write a function that gets the Ranges between the letters and then reads one range after another. OR: You use another library: here is a solution R read excel by column names