2016-10-05 102 views
0

我有一個數據集重複更換元件,稱爲鳴叫,像這樣:的R - 在數據幀

 V1  V2   V3 

1 pos  text1  text4 

2 neg  text2  text1 

3 neu  text3  text5 

在V2有3424個OBS,而在V3 1000個OBS。這些obs是從.txt文件導入的推文。 我想是這樣的:

 V1  V2   V3 

1 pos   NA  text4 

2 neg  text2  text1 

3 neu  text3  text5 

所以,如果在V2的元素是相同V3的元素,在V2的元素必須與NA取代。

我tryed使用此代碼:

x <- "N/A" 
for(i in 1:1000){ 
    for(l in 1:3424){ 
    if(full_corpus[i,3] == (full_corpus[l,2])){ 
    replace(full_corpus,l,x) 
}}} 

我不知道這是否是做到這一點的最好辦法,而我不知道真的很好如何「替換」的作品。

我收到此錯誤信息:

Error in Ops.factor(full_corpus[i, 3], (full_corpus[l, 2])) : 
    level sets of factors are different 

我怎麼能這樣做呢? 對不起,我今年在大學開始使用R和一般編碼,在這方面我仍然有很多困難。

我也是這個tryed:

library(dplyr) 
df %>% mutate(textA = ifelse(textA %in% textB, NA, textA)) 

但它不工作。我得到

This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information 

和R崩潰。我試圖重新安裝包的dplyr包,但我有相同的結果。

在此先感謝您的幫助。

回答

1

試試這個:

df[which(df$V2 %in% df$V3),]$V2 <- NA 
2

由於第一個錯誤,你在後提供。 我假設在讀取您的數據R轉換爲V2V3factors。 這是你得到錯誤的方法。因爲NAfactors中不是Level

但由於是factors現場得到了一個更容易一些: 你可以比較的V2V3levels並刪除levelsNA,發生在這兩個載體,所以你並不需要遍歷整個數據。

所以duplicates <- match(levels(V2),levels(V3))給你複製levelsV2

的位置,然後你可以只是刪除它們:

levels(V2)[duplicates] <- NA