2017-01-31 1 views
0

매우 간단한 질문이지만 해결책을 찾기 위해 고심 중입니다.변수 대체 - R

이로 가고 싶어 : 여기에

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 
,691을

솔루션은 정수에도 사용할 수 있습니까? 고맙습니다!

+0

본 적이 있습니까? http://stackoverflow.com/questions/19424709/r-gsub-pattern-vector-and-replacement-vector – joemienko

답변

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] 갈색 강아지 ""잔디가 녹색 "" "하늘이 파란색"

+1

감사합니다 @ 달라스 댈러스! – BlueDevilPride

+1

당신은'\'regmatches <- \'(df $ a, gregexpr ("color", df $ a), as.list (df $ b), invert = FALSE)와 같은 것을 할 수 있습니다. '실제로 더 빠릅니다. – thelatemail

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" 
당신이 선호하는 경우 stringi 패키지에서개

또는 사용 tidyverse

library(dplyr) 
df %>% 
    mutate(a = str_replace_all(a, 'color', b)) 
2

대부분의 기능은 그냥

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된다.

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"