如果此非 NA 字符并不總是出現在同一位置(第一行或其他位置),我正在嘗試找到一種方法,用非 NA 字符逐組替換一組值的 NA。我發現的解決方案不適用于字符或僅基于先前或后續值進行填充。
下面是一個資料示例:
participant_id <- c("ps1", "ps1", "ps1", "ps1", "ps2", "ps2", "ps3", "ps3", "ps3", "ps3")
test <- c("test1", NA, NA, NA, NA, "test2", NA, NA, "test3", NA)
data.frame(participant_id, test)
這就是我想要的結果:
| 參與者_id | 測驗 |
|---|---|
| ps1 | 測驗1 |
| ps1 | 測驗1 |
| ps1 | 測驗1 |
| ps1 | 測驗1 |
| ps2 | 測驗2 |
| ps2 | 測驗2 |
| ps3 | 測驗3 |
| ps3 | 測驗3 |
| ps3 | 測驗3 |
| ps3 | 測驗3 |
uj5u.com熱心網友回復:
我們可以使用fillfrom tidyrafter group by 'participant_id'
library(dplyr)
library(tidyr)
df1 <- df1 %>%
group_by(participant_id) %>%
fill(test, .direction = "downup") %>%
ungroup
-輸出
df1
# A tibble: 10 × 2
participant_id test
<chr> <chr>
1 ps1 test1
2 ps1 test1
3 ps1 test1
4 ps1 test1
5 ps2 test2
6 ps2 test2
7 ps3 test3
8 ps3 test3
9 ps3 test3
10 ps3 test3
資料
df1 <- data.frame(participant_id, test)
uj5u.com熱心網友回復:
這是使用na.locffromzoo包的另一種方法:
library(zoo)
library(dplyr)
df %>%
group_by(participant_id) %>%
arrange(participant_id, test) %>%
mutate(test = zoo::na.locf(test, na.rm=FALSE))
participant_id test
<chr> <chr>
1 ps1 test1
2 ps1 test1
3 ps1 test1
4 ps1 test1
5 ps2 test2
6 ps2 test2
7 ps3 test3
8 ps3 test3
9 ps3 test3
10 ps3 test3
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/338637.html
上一篇:如何使用R為8個組創建維恩圖?
下一篇:以R物件是否存在為條件保存它們
