Reputation: 155
Note: I am new to R and appreciate your help
The following is an elementary depiction of a much more complicated task I am seeking to perform. My data.table is named preferences
, and here is 2 objects I have defined:
col <- "Pref_1"
name <- "Economic Commission for Latin America and the Caribbean \\(ECLAC\\)"
I want to perform the following operation (1) :
preferences[, "Pref_1"] <- gsub(x = preferences[, c("Pref_1")], pattern = "Economic Commission for Latin America and the Caribbean \\(ECLAC\\)", replacement = "A")
However, I want to do so using my objects col
and name
such that (2):
preferences[, col] <- gsub(x = preferences[, col], pattern = name, replacement = "A")
Since I defined col
and name
outside the data.table, it seems that data.table is unable to use them in this operation. How can I tell R to read expression (1) as expression (2)?
Upvotes: 0
Views: 125
Reputation: 24732
I think you are trying to do the following:
preferences <- data.table(
Pref_1 = rep("Economic Commission for Latin America and the Caribbean (ECLAC)",3)
)
Pref_1
1: Economic Commission for Latin America and the Caribbean (ECLAC)
2: Economic Commission for Latin America and the Caribbean (ECLAC)
3: Economic Commission for Latin America and the Caribbean (ECLAC)
col = "Pref_1"
name = "Economic Commission for Latin America and the Caribbean \\(ECLAC\\)"
replacement = "A"
preferences[,(col):=gsub(Pref_1, pattern = name,replacement = replacement)]
Pref_1
1: A
2: A
3: A
Upvotes: 1