[英]In R: Replace NAs with values of other row but same value in other column
I have a much larger dataset.我有一个更大的数据集。 This is just a short example.
这只是一个简短的例子。 What i intend to do is to replace the NAs.
我打算做的是更换 NA。 Particularly, i want to replace them with the value that already exists for the same id.
特别是,我想用相同 id 已经存在的值替换它们。 I would prefer a pipe solution from dplyr.
我更喜欢 dplyr 的 pipe 解决方案。
ID <- c(1, 1, 1, 2, 2, 3, 3)
var <- c(NA, NA, 'M', 'F', NA, NA, 'M')
df <- data.frame(ID,var)
df %>% group_by(ID) #i am pretty sure that i need that
#df %>% replace_na(list(var)) #this is what i tried but does not work
The solution would be:解决方案是:
var <- c('M', 'M', 'M', 'F', 'F', 'M', 'M')
You can try with fill()
:您可以尝试使用
fill()
:
library(dplyr)
library(tidyr)
df %>%
group_by(ID) %>%
fill(var, .direction = "updown")
# A tibble: 7 x 2
# Groups: ID [3]
ID var
<dbl> <chr>
1 1 M
2 1 M
3 1 M
4 2 F
5 2 F
6 3 M
7 3 M
See Replace NA with values in another row of same column for each group in r Here is the solution of your question:请参阅将 NA 替换为 r 中每个组的同一列的另一行中的值以下是您问题的解决方案:
library(data.table)
setDT(df)[, var:= var[!is.na(var)][1L] , by = ID]
df
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.