填补数据框中的空白[重复](fill gap in dataframe [duplicate])

系统教程 行业动态 更新时间:2024-06-14 16:59:22
填补数据框中的空白[重复](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 answers

Original Data

id hhcode value 1 1 4.1 1 2 4.5 1 3 3.3 10 5 3.2

Required 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.2

What 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.2

Any 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.2

We 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

更多推荐

本文发布于:2023-04-16 19:08:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/d7f00ad3d8c5b538ce5001caf33fc001.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:框中   空白   数据   fill   dataframe

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!