2017-02-26 69 views
0

我試圖根據item_code列中的查找來填寫NA值。基本上,如果item_code有一個分配的部分,我希望它看看該行中的item_code,並檢查是否有一個部分分配給數據中的其他地方的代碼,如果是使用該或否則NA。這是一個龐大的數據集。如何根據R中的關聯填充缺失值

    item_code   section 
1     50406737    556 
2     48147401    NA 
3     49762314    NA 
4     47860166    557 
5     48147401    557 
6     49762314    NA 
7     49762314    554 
8     50884988    554 
9     50856064    NA 
10     49762314    554 
11     50868629    556 
12     51041955    556 
13     50856064    NA 
14     48147401    NA 
15     50460172    557 
16     50856064    559 
17     47860166    557 
18     50459661    557 

回答

1

這應該做(我在表中添加額外的item_code加入其中item_code只有在sectionNA值,這是從你的例子數據丟失的情況下通知)

require(tidyverse) 
df= read.table(text = 
"item_code   section 
1     50406737    556 
2     48147401    NA 
3     49762314    NA 
4     47860166    557 
5     48147401    557 
6     49762314    NA 
7     49762314    554 
8     50884988    554 
9     50856064    NA 
10     49762314    554 
11     50868629    556 
12     51041955    556 
13     50856064    NA 
14     48147401    NA 
15     50460172    557 
16     50856064    559 
17     47860166    557 
18     50459661    557 
19     50459662    NA", 
    header = TRUE 
) 

df2 <- df %>% 
    group_by(item_code) %>% 
    mutate(section = max(section, na.rm = T)) %>% 
    distinct(section) %>% 
    print() 

Source: local data frame [11 x 2] 
Groups: item_code [11] 

    section item_code 
    <int>  <int> 
1  556 50406737 
2  557 48147401 
3  554 49762314 
4  557 47860166 
5  554 50884988 
6  559 50856064 
7  556 50868629 
8  556 51041955 
9  557 50460172 
10  557 50459661 
11  NA 50459662 
的伎倆
+0

謝謝你的工作... – mickeyt500

+1

不客氣。我建議你看看這裏:https://cran.rstudio.com/web/packages/dplyr/vignettes/introduction.html fir與dplyr「數據爭奪」的一個很好的介紹。 – lbusett

+0

Lorenzo這兩列是更大數據框的一部分,我如何維護其他列呢?現在它只輸出them_code和section。在此先感謝 – mickeyt500