Tim Pigden - 4 months ago 24

R Question

gsub requires string arguments. But I'm want to process a whole array of string replacements. My sample code is as follows, but doesn't work

`pairs <- c(c("a", "b"), c("e", "f"))`

gsub("a", "b", "age")

#[1] "bge"

p1 <- pairs[1][1]

p1

#[1] "a"

p2 <- pairs[1][2]

gsub(p1, p2, "age")

#[1] NA

I'm sure this is fundamental thing about difference between vectors and strings but I don't know how to solve it. Apologies for what is doubtless a duplicate question but I've searched a lot of false leads in trying to google it

So with comment and answer from below I now understand:

Not really getting the "everything is a vector" I was making a false mental model that c("a", "b") turned characters into a vector of characters.

By extension I was thinking c(c("a", "b"), c("e", "f")) was creating a vector of vectors

But c("a", "b") is actually combining 2 single-element vectors into a single 2-element vector and by extension c(c("a", "b"), c("e", "f")) actually combines two 2-element vectors into a 4-element vector.

So matrices indeed is what I should have been working with in the first place.

Thanks guys!

Answer

Although you have `pairs`

as vector of character vectors. Ultimately if you check `pairs`

it gives as

```
pairs
#[1] "a" "b" "e" "f"
```

So you can use them with single indexing

```
p1 <- pairs[1]
p2 <- pairs[2]
gsub(p1, p2, "age")
#[1] "bge"
```