2016-08-04 153 views
0

我有一個數據框,看起來如下的方式。R填充空數據框

 Q  C  N 
    2  234  white 
    3  888  white 
    4  543  white 
    5  234  white 
    1  098  Blue 
    3  126  Blue 
    5  366  Black 
    1  222  pink 
    2  897  pink 

我希望數據框看起來像這樣。

 Q  C  N 
    1  555  white 
    2  234  white 
    3  888  white 
    4  543  white 
    5  234  white 
    1  098  Blue 
    2  0  Blue 
    3  126  Blue 
    4  0  Blue 
    5  0  Blue 
    1  0  Black 
    2  0  Black 
    3  0  Black 
    4  0  Black 
    5  366  Black 
    1  222  pink 
    2  897  pink 
    3  0  pink 
    4  0  pink 
    5  0  pink 

我希望它看起來像這樣。 的想法是,Q總是必須從1-5,如果它不出現我想數據框有一條線是質量是缺少它的名稱和填充0爲C. 謝謝

回答

3
library(tidyr) 
complete(df, Q, N, fill = list(C = 0)) 

得到你想要的(假設你的數據被稱爲df)。它對列和行進行重新排序,但如果需要,可以將其排序。


使用此數據作爲輸入:

df <- structure(list(Q = c(2L, 3L, 4L, 5L, 1L, 3L, 5L, 1L, 2L), C = c(234L, 
888L, 543L, 234L, 98L, 126L, 366L, 222L, 897L), N = structure(c(4L, 
4L, 4L, 4L, 2L, 2L, 1L, 3L, 3L), .Label = c("Black", "Blue", 
"pink", "white"), class = "factor")), .Names = c("Q", "C", "N" 
), class = "data.frame", row.names = c(NA, -9L)) 

df 
# Q C  N 
# 1 2 234 white 
# 2 3 888 white 
# 3 4 543 white 
# 4 5 234 white 
# 5 1 98 Blue 
# 6 3 126 Blue 
# 7 5 366 Black 
# 8 1 222 pink 
# 9 2 897 pink 

complete(df, Q, N, fill = list(C = 0)) 
# # A tibble: 20 x 3 
#  Q  N  C 
# <int> <fctr> <dbl> 
# 1  1 Black  0 
# 2  1 Blue 98 
# 3  1 pink 222 
# 4  1 white  0 
# 5  2 Black  0 
# 6  2 Blue  0 
# 7  2 pink 897 
# 8  2 white 234 
# 9  3 Black  0 
# 10  3 Blue 126 
# 11  3 pink  0 
# 12  3 white 888 
# 13  4 Black  0 
# 14  4 Blue  0 
# 15  4 pink  0 
# 16  4 white 543 
# 17  5 Black 366 
# 18  5 Blue  0 
# 19  5 pink  0 
# 20  5 white 234 
+0

聖鉬爲此在base R,我愛'dplyr'和'tidyr',但我直到現在還不知道'complete' :-)我曾經做過bleh%>%merge(bleh%>%group_by(a,b)%>%summarize(),all = T)%>%replace_na (list(c = 0))',這基本上是一樣的(我想, 比較慢) – AlexR

0

我們也可以expand.gridmerge

transform(merge(expand.grid(Q= unique(df$Q), N = unique(df$N)), 
       df, all.x=TRUE), C = replace(C, is.na(C), 0)) 
# Q  N C 
#1 1 Black 0 
#2 1 Blue 98 
#3 1 pink 222 
#4 1 white 0 
#5 2 Black 0 
#6 2 Blue 0 
#7 2 pink 897 
#8 2 white 234 
#9 3 Black 0 
#10 3 Blue 126 
#11 3 pink 0 
#12 3 white 888 
#13 4 Black 0 
#14 4 Blue 0 
#15 4 pink 0 
#16 4 white 543 
#17 5 Black 366 
#18 5 Blue 0 
#19 5 pink 0 
#20 5 white 234