NOTE: I am new to R and appreciate any and all help. We all start somewhere!
I want to perform the following operation on a project aimed at increasing my R skills:
preferences[, (cols) := gsub(cols, pattern = "UN1", replacement = "A")]
cols is a vector containing only one entry: the name of the column called "Pref_1". My objective is for R to replace all occurrences of "UN1" in the column "Pref_1" with the letter "A". Running the above code does not work, and instead pastes "Pref_1" in every single entry:
Pref_1
1: Pref_1
2: Pref_1
3: Pref_1
4: Pref_1
5: Pref_1
6: Pref_1
7: Pref_1
8: Pref_1
9: Pref_1
10: Pref_1
Through experimentation, I discovered that if I run an otherwise identical code, but instead replace the cols (which contains the characters "Pref_1") with Pref_1, the code executes as intended:
preferences[, (cols) := gsub(Pref_1, pattern = "UN1", replacement = "A")]
Pref_1
1: A
2: Food and Agriculture Organization (FAO)
3: United Nations Educational, Scientific and Cultural Organization (UNESCO)
4: United Nations Development Programme (UNDP)
5: Commission on Narcotic Drugs (CND)
6: Commission on Narcotic Drugs (CND)
7: Human Rights Council (HRC)
8: A
9: Human Rights Council (HRC)
10: A
Why wont gsub() allow me to reference the column I want to operate on using the cols object? The reason I am so persistent on using the cols object to reference the column I want to operate on is because I want to add column names to cols, and then run a for loop over the specified columns. Without using a cols vector to loop over, I would have to duplicate this code n times to operate over n columns.