How to remove a certain portion of the column name in a dataframe?

Viewed 41

I have column names in the following format:

col= c('UserLanguage','Q48','Q21...20','Q22...21',"Q22_4_TEXT...202")

I would like to get the column names without everything that is after ...

[1] "UserLanguage"    "Q48"             "Q21"        "Q22"        "Q22_4_TEXT"

I am not sure how to code it. I found this post here but I am not sure how to specify the pattern in my case.

2 Answers

You can use gsub.

gsub("\\...*","",col)

#[1] "UserLanguage" "Q48"     "Q21"        "Q22"     "Q22_4_TEXT"  

Or you can use stringr

library(stringr)

str_remove(col, "\\...*")

Since . matches any character, we need to "escape" (\) to specify exactly what we want to match in the regular expression (and not use the special behavior of the .). So, to match a period, we would need \.. However, the backslash (\) is used to escape special behavior (e.g., escape symbol in strings) in regexps. So, to create the regular expression, we need an additional backslash, \\. In this case, we want to match additional periods, so we can add those here, hence \\.... Then, * specifies that the previous expression (everything the three periods) may occur 0 or more times.

You could sub and capture the first word in each column:

col <- c("UserLanguage", "Q48", "Q21...20", "Q22...21", "Q22_4_TEXT...202")
sub("^(\\w+).*$", "\\1", col)

[1] "UserLanguage" "Q48"          "Q21"          "Q22"          "Q22_4_TEXT"

The regex pattern used here says to match:

^      from the start of the input
(\w+)  match AND capture the first word
.*     then consume the rest
$      end of the input

Then, using sub we replace with \1 to retain just the first word.

Related