我的问题是基于question。
我有如下数据。我想首先向下看,然后通过向上看,只要bom是相同的,就可以填充细胞。在bom = A的情况下,我想填充如图所示的行。但是在bom = B的情况下,由于type_p列不同,我想复制行并感觉空白
bom=c(rep("A",4),rep("B",3))
Part=c("","lambda","beta","","tim","tom","")
type_p=c("","sub","sub","","sub","pan","")
ww=c(1,2,3,4,1,2,3)
df=data.frame(bom,Part,type_p,ww)
> df
bom Part type_p ww
1 A 1
2 A lambda sub 2
3 A beta sub 3
4 A 4
5 B tim sub 1
6 B tom pan 2
7 B 3
我想要的最终数据如下
bom Part type_p ww
1 A lambda sub 1
2 A lambda sub 2
3 A beta sub 3
4 A beta sub 4
5 B tim sub 1
6 B tim sub 2
7 B tim sub 3
5 B tom pan 1
6 B tom pan 2
7 B tom pan 3
我想要的逻辑如下。请记住,我的数据非常庞大,每列中都有数千个值。
bom和ww列始终填充/填充传入数据
============================================ ===============更新2
在第3步之后,数据框将如下所示
> df
bom Part type_p ww
1 A lambda sub 1
2 A lambda sub 2
3 A beta sub 3
4 A beta sub 4
5 B tim sub 1
6 B 2
7 B 3
8 B 1
9 B tom pan 2
10 B 3
答案 0 :(得分:3)
使用tidyr
和dplyr
,您可以设法在您的目标附近做点什么
library(tidyr)
library(dplyr)
# replacing empty string with NA
df <- df %>% mutate_each(funs(sub("^$", NA, .)), Part, type_p)
# filling missing values
df <- df %>% fill(Part, type_p,.direction = "down") %>% fill(Part, type_p,.direction = "up")
df
#> bom Part type_p ww
#> 1 A lambda sub 1
#> 2 A lambda sub 2
#> 3 A beta sub 3
#> 4 A beta sub 4
#> 5 B tim sub 1
#> 6 B tom pan 2
#> 7 B tom pan 3
要获得您所描述的内容(有问题和评论),您可以处理BOM A&amp; B分开:
bind_rows(
df %>% filter(bom == "A"),
df %>% filter(bom == "B") %>%
complete(nesting(bom, Part, type_p), ww)
)
#> Source: local data frame [10 x 4]
#>
#> bom Part type_p ww
#> (fctr) (chr) (chr) (dbl)
#> 1 A lambda sub 1
#> 2 A lambda sub 2
#> 3 A beta sub 3
#> 4 A beta sub 4
#> 5 B tim sub 1
#> 6 B tim sub 2
#> 7 B tim sub 3
#> 8 B tom pan 1
#> 9 B tom pan 2
#> 10 B tom pan 3