0
df<-
  as.data.frame(cbind(Year = 2000:2004, matrix(
    round(runif(25, 50, 100), 0), nrow = 5, ncol = 5
  )))
names(df) <-
  c("Year", paste(rep("V", 5), seq(1:5), sep = ""))
df
#   Year V1 V2 V3 V4 V5
# 1 2000 69 65 94 80 85
# 2 2001 52 79 85 91 98
# 3 2002 85 67 87 61 61
# 4 2003 83 81 97 71 83
# 5 2004 62 77 73 52 96

colnames<- c("V1", "V2", "V6")

I have a dataset with a lot of columns (let say df) and a vector of names (lets say colnames). The vector has extra names which are not available in the dataset. How do I use this vector to select columns from the dataset.

select(df, colnames)
Error: Unknown column `V6` 
In addition: Warning message:
'glue::collapse' is deprecated.
Use 'glue_collapse' instead.
See help("Deprecated") and help("glue-deprecated"). 

I can not manually pick columnnames from either as there are a lot of columns.

ok1more
  • 779
  • 6
  • 15
  • 2
    `df[names(df) %in% colnames]` – Ronak Shah Sep 20 '18 at 02:32
  • 1
    `df %>% select(one_of(colnames))` should also work – mrjoh3 Sep 20 '18 at 02:47
  • @RonakShah it works! I tried to find it already existing questions but could not find out, perhaps I was not searching using the right keywords. I am wondering how did you find out that this question has been asked? Can you please point me to something that can be helpful. – ok1more Sep 20 '18 at 15:17

0 Answers0