首先,来自?merge:
两个数据框中与指定列匹配的行被提取并连接在一起。如果有多个匹配项,则所有可能的匹配项各贡献一行。
在 cmets 中使用您的链接:
url <- "http://koeppen-geiger.vu-wien.ac.at/data/KoeppenGeiger.UScounty.txt"
koppen <- read.table(url, header=T, sep="\t")
nrow(koppen)
# [1] 3594
length(unique(koppen$FIPS))
# [1] 2789
很明显koppen 有重复的 FIPS 代码。检查数据集和网站,似乎许多县都属于不止一个气候等级,例如,阿拉斯加的安克拉治县有三个气候等级:
koppen[koppen$FIPS==2020,]
# STATE COUNTY FIPS CLS PROP
# 73 Alaska Anchorage 2020 Dsc 0.010
# 74 Alaska Anchorage 2020 Dfc 0.961
# 75 Alaska Anchorage 2020 ET 0.029
解决方案取决于您要完成的任务。如果您想提取all 中的所有行以及出现在koppen 中的任何FIPS,则这些都应该可以工作:
merge(all,unique(koppen$FIPS))
all[all$FIPS %in% unique(koppen$FIPS),]
如果您需要将县和州名称附加到 all,请使用:
merge(all,unique(koppen[c("STATE","COUNTY","FIPS")]),by="FIPS")
编辑基于以下 cmets 中的交流。
因此,由于有时koppen 中的多行具有相同的FIPS,但不同的CLS,我们需要一种方法来决定选择哪一行(例如,哪一行CLS)。这里有两种方法:
# this extracts the row with the largest value of PROP, for that FIPS
url <- "http://koeppen-geiger.vu-wien.ac.at/data/KoeppenGeiger.UScounty.txt"
koppen <- read.csv(url, header=T, sep="\t")
koppen <- with(koppen,koppen[order(FIPS,-PROP),])
sub.koppen <- aggregate(koppen,by=list(koppen$FIPS),head,n=1)
result <- merge(all, sub.koppen, by="FIPS")
# this extracts a row at random
sub.koppen <- aggregate(koppen,by=list(koppen$FIPS),
function(x)x[sample(1:length(x),1)])
result <- merge(all, sub.koppen, by="FIPS")