使用merge
函数连接2个data.frame我发现它的参数sort
没有任何改变。例如:
id_df <- structure(list(id = c("click", "event", "funnel", "impression",
"tracker", "visibility"),
id_Havas = c("a1", "a2", "a3", "a4", "a5", "a6")),
.Names = c("id", "my_id"), class = "data.frame",
row.names = c(NA, -6L))
my_df <- data.frame("id" = c("click", "click", "impression", "visibility", "click"),
stringsAsFactors = F)
结果:
my_df
# id
# 1 click
# 2 click
# 3 impression
# 4 visibility
# 5 click
merge(my_df, id_df, by = "id", all.x = TRUE, sort = FALSE)
# id my_id
# 1 click a1
# 2 click a1
# 3 click a1
# 4 impression a4
# 5 visibility a6
merge(my_df, id_df, by = "id", all.x = TRUE, sort = TRUE)
# id my_id
# 1 click a1
# 2 click a1
# 3 click a1
# 4 impression a4
# 5 visibility a6
我错过了什么吗?
答案 0 :(得分:1)
要保留原始订单,您可以使用match
:
my_df$my_id <- id_df$my_id[match(my_df$id, id_df$id)]
my_df
# id my_id
#1 click a1
#2 click a1
#3 impression a4
#4 visibility a6
#5 click a1
根据您的具体情况,merge
和match
之间的基准比较,考虑到my_df
的60000种不同的ID和100000行:
f_merge <- function(){merge(my_df, id_df, by = "id", all.x = TRUE, sort = FALSE)}
f_match <- function(){my_df$my_id <- id_df$my_id[match(my_df$id, id_df$id)]}
microbenchmark(f_match(), f_merge(), unit="relative")
# expr min lq mean median uq max neval cld
#f_match() 1.00000 1.00000 1.00000 1.00000 1.00000 1.000000 100 a
#f_merge() 41.16602 46.42379 26.62328 47.59711 17.28836 7.176999 100 b
sort
中的参数merge
如何运作:
来自?merge
,&#34;价值&#34;部分,你可以阅读:
默认情况下,行按字典顺序在公共列上排序,但对于sort = FALSE,行的顺序是未指定的。
因此,所有常见名称都是&#34;放在一起&#34;但如果sort=FALSE
,则不会对唯一名称进行排序。
<强> 实施例 强>
my_df <- data.frame("id" = c("impression", "click", "click", "impression", "visibility", "click"), stringsAsFactors = F)
merge(my_df, id_df, by = "id", all.x = TRUE, sort = FALSE)
# id my_id
#1 impression a4
#2 impression a4
#3 click a1
#4 click a1
#5 click a1
#6 visibility a6
merge(my_df, id_df, by = "id", all.x = TRUE, sort = TRUE)
# id my_id
#1 click a1
#2 click a1
#3 click a1
#4 impression a4
#5 impression a4
#6 visibility a6