简体   繁体   English

在 R 中:将 NA 替换为其他行的值,但其他列中的值相同

[英]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.

相关问题 如何将 B 列中的值替换为 B 列中与 R 中 A 列中相同值关联的其他值? - How do I replace values in column B with other values in column B associated with the same value in column A in R? 如何根据R中的其他列将NA替换为先前的列值加上一个分组? - How to replace NAs with previous column values plus one by group based on other columns in R? R:如何使用来自利用其他多列的条件的值替换 dataframe 列中的 NA? - R: How do I replace NAs in a dataframe column with values from conditions leveraging other multiple columns? 根据同一列中的其他行值替换 R 数据框中的行值 - Replacing row values in R data frame based on other row value in same column 如何将 dataframe 中的任何 NA 替换为 R 中同一行中的先前值 - How to replace any NAs in dataframe with the previous value in the same row in R R中的data.table:在匹配其他两个列值后,用相同列中的值替换列值 - data.table in R: Replace a column value with a value from same column after matching two other columns values R-根据应用于同一行中其他值的函数设置值 - R - setting a value based on a function applied to other values in the same row dplyr 的 rowwise + replace_NAs:用其他列的值替换多列中的 NA - dplyr's rowwise + replace_NAs: replacing NAs in multiple columns with value from other column 使用其他列的值替换列中的NA - Replacing NAs in a column with the values of other column 用同一列的单个值替换列的 NA - replace NAs of a column with the single value of the same column
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM