AaronSzcz
AaronSzcz

Reputation: 155

Referencing vectors outside a data.table to perform operations

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

Answers (1)

langtang
langtang

Reputation: 24732

I think you are trying to do the following:

Set up a simple example table

preferences <- data.table(
  Pref_1 = rep("Economic Commission for Latin America and the Caribbean (ECLAC)",3)
)

This is what it looks like before trying to replace anything

                                                            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)

Now set up your col, pattern, and replacement

col = "Pref_1"
name = "Economic Commission for Latin America and the Caribbean \\(ECLAC\\)"
replacement = "A"

Execute the replacement (notice that I wrap col in parentheses

preferences[,(col):=gsub(Pref_1, pattern = name,replacement = replacement)]

This is what it looks like now

  Pref_1
1:      A
2:      A
3:      A

Upvotes: 1

Related Questions