Reputation: 427
Below is some background information about my dataset if you want to understand where my question comes from (I actually want to merge datasets, so maybe somebody knows a more efficient way).
The question: How to replace only the final character of a variable name in R with nothing (for multiple variables)?
I tried using the sub() function and it worked fine, however, some variable names contain the character I want to change multiple times (e.g. str2tt2). I only want to 'remove' or replace the last '2' with blank space.
Example: Suppose I have a dataset with these variable names, and I only want to remove the last '_2' characters, I tried this:
h_2ello_2 how_2 are_2 you_2
1 1 3 5 7
2 2 4 6 8
names(data) <- sub('_2', '', names(data))
Output:
hello_2 how are you
1 1 3 5 7
2 2 4 6 8
Now, I want my code to remove the last '_2', so that it returns 'h_2ello' instead of hello_2.
Does anyone know how to? Thank you in advance!
Background information:
I am currently trying to build a dataset from three separate ones. These three different ones are from three different measurement moments, and thus their variable names include a character after each variable name respective to their measurement moment. That is, for measurement moment 2, the variable names are scoreA2, scoreB2, scoreC2 and for measurement moment 3, the variable names are scoreA3, scoreB3 and scoreC3.
Since I want to merge these files together, I want to remove the '2' and '3' in the datasets and then merge them so that it seems like everyone was measured at the same moment.
However, some score names include the character 2 and 3 as well. For example: str2tt2 is the variable name for Stroop card 2 total time measurement moment 2. I only want to remove the last '2', but when using the sub() function I only remove the first one.
Upvotes: 4
Views: 939
Reputation: 887501
We need to use the metacharacter $
suggesting the end of the string on the original dataset column names
names(data) <- sub('_2$', '', names(data))
names(data)
#[1] "h_2ello" "how" "are" "you"
In the OP's code, the _2
matches the first instance in h_2ello_2
as it is sub
and removes the _2
from h_2
. Instead we need to specify the position to be the last characters of the string.
Upvotes: 1