![](/img/trans.png)
[英]Fill NA in R: imput NA in a column X with values from same ID (column Y ) correspondance
[英]R dplyr full_join(x, y): fill NA with values from x
我想聯合兩個數據框:
library(dplyr)
set.seed(666)
x <- data.frame(id = 1:10, c1 = rnorm(10), c2 = rnorm(10), c3 = rnorm(10))
y <- data.frame(id = 1:10, c1 = rnorm(10))
joined <- x |>
full_join(y) |>
arrange(id)
用x
的列中的值填充y
中新行的 NA 的優雅方法是什么?
目標:
id c1 c2 c3
1 1 0.75331105 2.15004262 -0.69209929
2 1 0.75499616 2.15004262 -0.69209929
3 2 2.01435467 -1.77023084 -1.18304354
4 2 -0.64148890 -1.77023084 -1.18304354
...
編輯: tidyr::fill() 工作正常,但在中等大型數據集(例如>100k 行,>20cols)上似乎非常慢。 我很高興看到 data.table 替代方案
添加另一行代碼。
選擇您需要fill.
編輯:在這種情況下不需要分組。 因為每個新組都以一個數字開頭。
joined <- x |>
full_join(y) |>
arrange(id) |>
fill(c2:c3, .direction = "down")
id c1 c2 c3
<int> <dbl> <dbl> <dbl>
1 1 -0.0822 1.18 -0.889
2 1 1.58 1.18 -0.889
3 2 0.120 0.0288 0.278
4 2 1.64 0.0288 0.278
5 3 0.0213 -0.166 -1.20
6 3 -0.404 -0.166 -1.20
7 4 -0.274 -1.53 -0.660
8 4 -0.0456 -1.53 -0.660
9 5 -0.881 -0.335 -1.02
10 5 -2.47 -0.335 -1.02
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.