maduba
maduba

Reputation: 1

Select column names by partial string match

i want to select columns from a data frame by name. the names of the columns are in a separate list, but the names in the list and the names of the columns are not exactly the same.

so here's my code:

list.of.names <- c('Var_1', 'Var_2')

But the column names are like this 'Var.1', Var.2'

I tried it with this:

new.df <- old.df %>% select(c(list.of.names))

Is there any function that does not distinguish between '.' and '_'?

Thanks for the help!

Upvotes: 0

Views: 878

Answers (1)

doing_my_best
doing_my_best

Reputation: 19

If I understand right you need the names in the list to match the column names exactly. AS MrFlick said, use gsub to replace the _ with .

gsub("_", ".", list.of.names) should work

However, I would recommend not using periods in column names or anything other than functions because it is confusing to keep things separate. I always use _ in variable names and I think it is maybe standard practice. Others can correct me if I am wrong.

This discussion gives more details. Replace specific characters within strings

Upvotes: 1

Related Questions