[英]Using R to insert a value for missing data with a value from another data frame
所有,
我有一個問題,我擔心這可能太行人了,但在其他地方尋找它會讓我誤入歧途。 我可能沒有使用正確的搜索字詞。
我在R中有一個面板數據框(country-year),在給定變量上有一些缺失值。 我試圖用另一個數據框中另一個向量的值來估算它們。 這是我想要做的一個例子。
假設Data
是感興趣的數據幀,它在我試圖從另一個施主數據幀推斷的給定向量上具有缺失值。 看起來像這樣。
country year x
70 1920 9.234
70 1921 9.234
70 1922 9.234
70 1923 9.234
70 1924 9.234
80 1920 NA
80 1921 NA
80 1922 NA
80 1923 NA
80 1924 NA
90 1920 7.562
90 1921 7.562
90 1922 7.562
90 1923 7.562
90 1924 7.562
這將是Donor
框架,其具有country == 80
的值
country x
70 9.234
80 1.523
90 7.562
我試圖找到一種無縫的自動化方法,除了Data$x[Data$country == 80] <- 1.523
。 有很多國家在x
上缺席。
可能值得澄清的是,簡單的merge
將是最簡單的,但不一定適合我正在嘗試做的事情。 一些國家將在不同年份看到x
變化。 基本上,我想要完成的是一個命令,如果某個國家/地區的所有年份的Data
缺少x
的值,請從Donor
數據中獲取該國家/地區的相應值並將其粘貼到所有國家/地區年份作為各種“最好的猜測”。
感謝您的任何意見。 我懷疑這是一個菜鳥問題,但我不知道搜索它的正確術語。
以下數據的可重現代碼如下。
country <- c(70,70,70,70,70,80,80,80,80,80,90,90,90,90,90)
year <- c(1920,1921,1922,1923,1924,1920,1921,1922,1923,1924,1920,1921,1922,1923,1924)
x <- c(9.234,9.234,9.234,9.234,9.234,NA,NA,NA,NA,NA,7.562,7.562,7.562,7.562,7.562)
Data=data.frame(country=country,year=year,x=x)
summary(Data)
country <- c(70,80,90)
x <- c(9.234,1.523,7.562)
Donor=data.frame(country=country,x=x)
summary(Donor)
使用merge
:
r = merge(Data, Donor, by="country", suffixes=c(".Data", ".Donor"))
Data$x = ifelse(is.na(r$x.Data), r$x.Donor, r$x.Data)
如果出於某種原因想要覆蓋x的所有值看起來很糟糕,那么使用which
只覆蓋NAs(具有相同的合並):
r = merge(Data, Donor, by="country", suffixes=c(".Data", ".Donor"))
na.idx = which(is.na(Data$x))
Data[na.idx,"x"] = r[na.idx,"x.Donor"]
這是一個選項,通常應該工作:
#Get the vector of countries with missing x
country.na <- Data$country[is.na(Data$x)]
#Get corresponding location of x in Donor
index <- sapply(country.na, function(x) which(Donor$country == x))
#Replace NA values with corresponding values in Donor
Data$x[is.na(Data$x)] <- Donor$x[index]
Data
# country year x
# 1 70 1920 9.234
# 2 70 1921 9.234
# 3 70 1922 9.234
# 4 70 1923 9.234
# 5 70 1924 9.234
# 6 80 1920 1.523
# 7 80 1921 1.523
# 8 80 1922 1.523
# 9 80 1923 1.523
# 10 80 1924 1.523
# 11 90 1920 7.562
# 12 90 1921 7.562
# 13 90 1922 7.562
# 14 90 1923 7.562
# 15 90 1924 7.562
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.