R填充空数据框
问题描述:
我有一个数据框,看起来如下的方式。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. 谢谢
答
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
答
我们也可以expand.grid
和merge
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
圣钼为此在
base R
,我爱'dplyr'和'tidyr',但我直到现在还不知道'complete' :-)我曾经做过bleh%>%merge(bleh%>%group_by(a,b)%>%summarize(),all = T)%>%replace_na (list(c = 0))',这基本上是一样的(我想, 比较慢) – AlexR