2017-02-26 73 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