填补数据框中的空白[重复](fill gap in dataframe [duplicate])
这个问题在这里已有答案:
将默认值添加到没有值的项目x组对(df%>%spread%>%gather看起来很奇怪) 2个答案原始数据
id hhcode value 1 1 4.1 1 2 4.5 1 3 3.3 10 5 3.2要求的输出
id hhcode value 1 1 4.1 1 2 4.5 1 3 3.3 1 5 0 10 1 0 10 2 0 10 3 0 10 5 3.2到目前为止
df <- data.frame( id = c(1, 1, 1, 10), hhcode = c(1, 2, 3, 5), value = c(4.1, 4.5, 3.3, 3.2) ) library(statar) library(tidyverse) df %>% group_by(id) %>% fill_gap(hhcode, full = TRUE) # A tibble: 10 x 3 # Groups: id [2] id hhcode value <dbl> <dbl> <dbl> 1 1 1 4.1 2 1 2 4.5 3 1 3 3.3 4 1 4 NA 5 1 5 NA 6 10 1 NA 7 10 2 NA 8 10 3 NA 9 10 4 NA 10 10 5 3.2任何提示获得所需的输出?
This question already has an answer here:
adding default values to item x group pairs that don't have a value (df %>% spread %>% gather seems strange) 2 answersOriginal Data
id hhcode value 1 1 4.1 1 2 4.5 1 3 3.3 10 5 3.2Required Output
id hhcode value 1 1 4.1 1 2 4.5 1 3 3.3 1 5 0 10 1 0 10 2 0 10 3 0 10 5 3.2What got so far
df <- data.frame( id = c(1, 1, 1, 10), hhcode = c(1, 2, 3, 5), value = c(4.1, 4.5, 3.3, 3.2) ) library(statar) library(tidyverse) df %>% group_by(id) %>% fill_gap(hhcode, full = TRUE) # A tibble: 10 x 3 # Groups: id [2] id hhcode value <dbl> <dbl> <dbl> 1 1 1 4.1 2 1 2 4.5 3 1 3 3.3 4 1 4 NA 5 1 5 NA 6 10 1 NA 7 10 2 NA 8 10 3 NA 9 10 4 NA 10 10 5 3.2Any hint to get the required output?
最满意答案
我们可以使用complete
library(tidyverse) complete(df, id, hhcode, fill = list(value = 0)) # A tibble: 8 x 3 # id hhcode value # <dbl> <dbl> <dbl> #1 1 1 4.1 #2 1 2 4.5 #3 1 3 3.3 #4 1 5 0 #5 10 1 0 #6 10 2 0 #7 10 3 0 #8 10 5 3.2We could use complete
library(tidyverse) complete(df, id, hhcode, fill = list(value = 0)) # A tibble: 8 x 3 # id hhcode value # <dbl> <dbl> <dbl> #1 1 1 4.1 #2 1 2 4.5 #3 1 3 3.3 #4 1 5 0 #5 10 1 0 #6 10 2 0 #7 10 3 0 #8 10 5 3.2更多推荐
发布评论