非常简单的问题,但我很难找到解决方案。
想要离开:
a = c("the sky is color", "the color dog", "grass is color")
b = c("blue","brown","green")
df = data.frame(a,b)
对此:
a = c("the sky is color", "the color dog", "grass is color")
b = c("blue","brown","green")
c = c("the sky is blue", "the brown dog", "grass is green")
df = data.frame(a,b,c)
尝试使用gsub:
df$d <- gsub('color', df$b, df$a)
但收到此错误消息:
argument 'replacement' has length > 1 and only the first element will be used
该解决方案是否也适用于整数?谢谢!
答案 0 :(得分:2)
我认为这是一个简洁的矢量化解决方案,但您可以使用简单的apply
语句来完成它。
a = c("the sky is color", "the color dog", "grass is color")
b = c("blue","brown","green")
df = data.frame(a,b)
df$d <- apply(df,1,function(x){gsub('color', x[2], x[1])})
df$d
[1]&#34;天空是蓝色的&#34; &#34;棕色的狗&#34; &#34;草是绿色的&#34;
答案 1 :(得分:2)
stringi
包中的大多数函数都是矢量化的,所以你可以这样做
df$c <- stringi::stri_replace_all_fixed(df$a, 'color', df$b)
df
## a b c
## 1 the sky is color blue the sky is blue
## 2 the color dog brown the brown dog
## 3 grass is color green grass is green
如果您愿意,可以在dplyr或data.table中实现。
答案 2 :(得分:0)
我们可以使用mapply
df$a <- mapply(sub, 'color', df$b, df$a)
df$a
#[1] "the sky is blue" "the brown dog" "grass is green"
或者我们可以使用str_replace_all
stringr
library(stringr)
df$a <- str_replace_all(df$a, 'color', df$b)
df$a
#[1] "the sky is blue" "the brown dog" "grass is green"
或使用tidyverse
library(dplyr)
df %>%
mutate(a = str_replace_all(a, 'color', b))
答案 3 :(得分:0)
有Vectorize
函数可以让你指定一些矢量化参数。在这种情况下,您希望对“替换”参数和名为“x”的字符串参数进行矢量化:
(df$c <- Vectorize(gsub, c("replacement", "x"))("color", df$b, df$a, fixed = TRUE))
# [1] "the sky is blue" "the brown dog" "grass is green"