2017-12-31 129 views
1

저는 R을 쳐다 보았고 두 개의 서로 다른 테이블의 두 열을 비교하려고했습니다. 일치하는 항목이 true이면 df1의 특정 값을 바꿉니다. 나는 데이터베이스에 스크립트를 사용하고 싶기 때문에 추가 패키지를 사용하는 것에 대해 매우 제한적이라는 문제점이있다.프레임/테이블 특정 행을 비교하고 바꿉니다.

DF1 :

DE 
Deutschland 
England 
Germany 
Italien 

결과

GE    EN 
Deutschland  Germany 
Italien   Italy 
England   UK 

DF2 : DF1 :

DE 
Deutschland 
England 
**Deutschland** 
Italien 

내가 노력 코드를 다음

df1 <- data.frame("DE" = c("Deutschland", "England", "Germany", "Italien")) 
df2 <- data.frame("GE" = c("Deutschland", "Italien", "England"), "EN" = c("Germany", "Italy", "UK")) 
df1[] <- lapply(df1, as.character) 
df2[] <- lapply(df2, as.character) 

df1 <- ifelse(!(df1$DE %in% df2$EN), df1$DE, df2$GE) 

"Deutschland"대신 "England"를 대체합니다. 올바른 행을 어떻게 바꿀 수 있습니까?

답변

6

nomatch -operator으로 match를 사용 가능한 용액 : 범

df1$DE[df1$DE %in% df2$EN] <- df2$GE[match(df1$DE, df2$EN, nomatch = 0)] 

:

> df1 
      DE 
1 Deutschland 
2  England 
3 Deutschland 
4  Italien 

를이 기능 :

  • 012,350,720,239,은 교체가 필요한 df1의 행을 나타냅니다.
  • df2$GE[match(df1$DE, df2$EN, nomatch = 0)]은 대체품을 df2에서 선택합니다.
  • 후자는 전호에 <-으로 지정할 수 있습니다.

으로는 %in%는 후드 match을 사용 the comments에 @ r2evans에 의해 지적했다. 그 지식을 바탕으로 당신은 할 수 : 인덱스 ind 이제 한 번만 작성

ind <- match(df1$DE, df2$EN, nomatch = 0) 
df1$DE[ind > 0] <- df2$GE[ind] 

때문에이 큰 데이터 세트에 상당한 spead 증가로 이어질 수있다. 또한 갱신이 할 수


data.table과 조인

같은 결과를 제공
# load the package 
library(data.table) 

# convert the dataframes to data.table's 
setDT(df1) 
setDT(df2) 

# perform the update join 
df1[df2, on = .(DE = EN), DE := GE][] 

는 :

  DE 
1: Deutschland 
2:  England 
3: Deutschland 
4:  Italien 
+2

''%에서 %는 '일치를 사용 '. 큰 데이터 세트를 사용하면'df1 $ DE [ind> 0] <- df2 $ GE [ind]'뒤에'ind <- match (df1 $ DE, df2 $ EN, nomatch = 0)'을 사용하는 것이 유리할 수 있습니다. (이 작은 데이터 세트를 사용하면 이미 30 % 정도 더 빠르지 만 시간 차이는 크지 않습니다.) – r2evans

+0

답변 해 주셔서 감사합니다. :) –

+1

@ r2evans thx & added :-) – Jaap