用相邻行R中的重复项替换NA
我有一个数据集,其中包含用相邻行R中的重复项替换NA,r,na,R,Na,我有一个数据集,其中包含日期、年龄和客户ID。Age中的一些行中缺少值(NAs),我想对它们进行插补 以下是一些示例数据: Date <- c("201101", "201102", "201101", "201102", "201103") Age <- c("12-17", "12-17", "30-35", NA, NA) Customer_ID <- c("1234", "1234", "5678", "5678", "5678") df <- data.fram
日期
、年龄
和客户ID
。Age
中的一些行中缺少值(NAs),我想对它们进行插补
以下是一些示例数据:
Date <- c("201101", "201102", "201101", "201102", "201103")
Age <- c("12-17", "12-17", "30-35", NA, NA)
Customer_ID <- c("1234", "1234", "5678", "5678", "5678")
df <- data.frame(Date, Age, Customer_ID)
Date Age Customer_ID
201101 12-17 1234
201102 12-17 1234
201101 30-35 5678
201102 NA 5678
201103 NA 5678
Date您可以从tidyr
使用fill
功能。它是一个tidyr
功能,用于结转最后一次观察,即用以前的非NA值填充NA值。为了实现这一点,您可以使用arrange
对列2进行排序,该列对非NAs后面的NA
值进行排序,然后您可以按客户ID分组并填写Age
列:
library(dplyr)
library(tidyr)
df %>% arrange(Age) %>% group_by(Customer_ID) %>% fill(Age)
# Source: local data frame [5 x 3]
# Groups: Customer_ID [2]
# Date Age Customer_ID
# <fctr> <fctr> <fctr>
# 1 201101 12-17 1234
# 2 201102 12-17 1234
# 3 201101 30-35 5678
# 4 201102 30-35 5678
# 5 201103 30-35 5678
库(dplyr)
图书馆(tidyr)
df%%>%排列(年龄)%%>%分组依据(客户ID)%%>%填充(年龄)
#来源:本地数据帧[5 x 3]
#组别:客户识别码[2]
#日期年龄客户识别码
#
# 1 201101 12-17 1234
# 2 201102 12-17 1234
# 3 201101 30-35 5678
# 4 201102 30-35 5678
# 5 201103 30-35 5678
带基数R:
lookup <- unique(df[!is.na(df$Age),][c('Customer_ID', 'Age')])
df[is.na(df$Age),]$Age <- lookup[match(df[is.na(df$Age),]$Customer_ID,
lookup$Customer_ID),]$Age
lookup@SamFirke你说得对,谢谢你的链接。