How to keep last column of same column names?

Viewed 68
Patient Patient
chris chris
chris jake
tom alvin

As you can see there are same column name but I only want the those on the right.

Sample code

x = read_excel(path, sheet=1)
df = data.frame(x)
df <- df [, !duplicated(colnames(df), fromLast = TRUE)] 

But the output is wrong.

1 Answers

readxl::read_excel() has the argument .name_repair to control how duplicated column names are handled when importing an Excel file. By default it is set to "check_unique". Try .name_repair = "minimal". You may want to check other options, see ?tibble, Arguments section.

x <- readxl::read_excel("./test.xlsx", .name_repair = "minimal")
df <- x[, !duplicated(colnames(x), fromLast = TRUE)]

Output:

> df
# A tibble: 3 x 4
  Hospital  Ward Patient Staff
  <chr>    <dbl> <chr>   <chr>
1 abc        123 chris   Jen  
2 def        456 ron     Jen  
3 ghi        123 harry   Jen 
Related