R 为什么合并会产生比原始数据更多的行?

R 为什么合并会产生比原始数据更多的行?,r,join,R,Join,当我合并两个数据帧时,结果的行数比原始数据的行数多 在这种情况下,all数据框有104956行,koppen有3968行,alltest数据框有130335行。通常,alltest的行数应等于或小于all 为什么会发生这种通货膨胀?我不确定给出可复制的示例是否会有所帮助,因为它在我之前使用过的实例中确实有效 alltest <- merge(all, koppen, by = "fips", sort = F) alltest首先,从?合并: 将提取两个数据帧中与指定列匹配的行,并将其连

当我合并两个数据帧时,结果的行数比原始数据的行数多

在这种情况下,all数据框有104956行koppen3968行alltest数据框有130335行。通常,alltest的行数应等于或小于all


为什么会发生这种通货膨胀?我不确定给出可复制的示例是否会有所帮助,因为它在我之前使用过的实例中确实有效

alltest <- merge(all, koppen, by = "fips", sort = F)

alltest首先,从
?合并

将提取两个数据帧中与指定列匹配的行,并将其连接在一起。如果有多个匹配项,则所有可能的匹配项都会贡献一行

使用评论中的链接:

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
中的任何
fip
提取
all
中的所有行,则应使用以下任一选项:

merge(all,unique(koppen$FIPS))

all[all$FIPS %in% unique(koppen$FIPS),]
如果需要将县和州名称附加到
all
,请使用以下命令:

merge(all,unique(koppen[c("STATE","COUNTY","FIPS")]),by="FIPS")
根据下面评论中的交流进行编辑

因此,由于在
koppen
中有时有多行具有相同的
fip
,但不同的
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")
#这将为该FIPS提取PROP值最大的行

url可能是因为两个数据帧中的一个具有重复的值
fips
。哦,等等,在所有的数据帧中都有重复的fips。它不应该是独一无二的。知道如何在不增加这些行的情况下进行合并吗?
nrow(koppen)==length(unique(koppen$fips))
返回
TRUE
?如果没有,则存在重复的
fips
值,您如何在不增加行数的情况下明确地合并它们?“我不确定给出可复制的示例是否会有所帮助,因为它在我以前使用过的示例中确实有效。”一个可复制的例子应该可以重现您遇到的问题。稍后我会尝试。先生,您是一个救生员。谢谢。:)好的,有一个问题,我当然也需要上课。当我使用merge(all,unique(koppen[c(“STATE”,“country”,“CLASS”,“FIPS”))])、by=“FIPS”)时,它再次超过了所需的行数。但当我只使用州、县、fips时,代码运行良好。为什么?对于给定的FIP,可以有多个类。你想要哪一班?如果您想要所有这些,那么会有重复的FIP。问题是,对于给定的FIP,
koppen
中有多个CLS。因此,如果您想要所有这些,那么在合并中每个FIP将获得多行。以Ankorage为例。如果
all
有一行FIPS=2020,并且您希望所有三个CLS都来自
koppen
,那么您将在FIPS=2020的合并中有三行。如果
all
有多个FIPS=2020的行,那么对于FIPS=2020的
all
中的每一行,结果中将有三行。
# 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")