I feel like this has to be a super basic thing to solve but my searching skills are failing me.
df <- data.frame(col1 = c("abc", "def", "ghi"),
col2 = c("foo ~xyz~", "~xyz~ bar", "blah ~xyz~ blah"))
col1 col2
abc foo ~xyz~
def ~xyz~ bar
ghi blah ~xyz~ blah
I want to gsub()
each row of col1
into the corresponding ~xyz~
token in col2
. The desired output is:
col1 col2
abc foo abc
def def bar
ghi blah ghi blah
I can solve this using a for
loop but I feel like there's got to be a way to do this with vapply
or sapply
.
My for
loop solution is as follows:
for (i in 1:nrow(df)) {
itemhold <- df$col1[i]
df$col2[i] <- gsub("~xyz~", itemhold, df$col2[i])
}
Any tips would be greatly appreciated. If it's not painfully obvious by now, I'm fairly new to R and it's my first language.
Edit: I deleted some stuff about a function I used for these purposes because as I actually worked through my minrep example I realized it wasn't needed--I use the function in a special case that isn't really relevant here.
You can do this with stringr
without any looping or apply
ing:
df <- data.frame(col1 = c("abc", "def", "ghi"),
col2 = c("foo ~xyz~", "~xyz~ bar", "blah ~xyz~ blah"),
stringsAsFactors = FALSE)
df$col2_replaced = str_replace(df$col2, "~xyz~", df$col1)
Output:
> df
col1 col2 col2_replaced
1 abc foo ~xyz~ foo abc
2 def ~xyz~ bar def bar
3 ghi blah ~xyz~ blah blah ghi blah
You can do this with apply
like so:
df$col2 <- apply(df, 1,
function(row) gsub(pattern="~xyz~", replacement=row["col1"], x=row["col2"]))
# col1 col2
# 1 abc foo abc
# 2 def def bar
# 3 ghi blah ghi blah
Here it is with mapply
(aka "multivariate apply") instead:
df$col2 <- mapply(
function(rep, string) gsub(pattern="~xyz~", replacement=rep, x=string),
df$col1, df$col2)
# col1 col2
# 1 abc foo abc
# 2 def def bar
# 3 ghi blah ghi blah
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.