我有两个数据帧,我必须合并。在两个数据帧中都有一列,我希望在该列上合并两个数据帧。但这两列中的数据并不相似。这两个数据帧中的关键列的长度为12位,另一个数据帧的长度为5 -6位。我想合并的基础上类似的5-6位从第二个数据帧。
我的数据框:
df1 = data.frame(CustomerId = c(987689000000,786581000000,765909000000,565400000000,746541000000,516890000000), Product = c(rep("Toaster", 3), rep("Radio", 3)))
df2 = data.frame(customerId = c(987689,986581,7659090,56540,74651,5168900), State = c(rep("Alabama", 2), rep("Ohio", 1)))我试过c = merge(df1,df2 , key =("CustomerId "),all = TRUE)
我的预期输出如下:
CustomerId Product State
1 987689 Toaster Alabama
2 786581 Toaster Alabama
3 7659090 Toaster Alabama
4 56540 Radio Alabama
5 74651 Radio Alabama
6 516890 Radio Alabama发布于 2017-07-13 13:44:18
这是一个解决方案。关键是使用formatC调整数字的格式,并使用str_extract提取匹配的部分。完成此步骤后,您可以确定是要使用left_join、right_join还是inner_join来保留数据帧的哪一部分。df3是最终输出。
请注意,您提供的示例包含不匹配的ID,因此根据您提供的数据框不可能重现所需的输出。
# Load packages
library(dplyr)
library(stringr)
library(rebus)
# Process the data
df3 <- df1 %>%
# Use str_extract to get CustomerId matched in df2
mutate(CustomerId = str_extract(string = formatC(CustomerId,
digits = 0,
format = "f"),
pattern = or1(df2$customerId))) %>%
# Join with df2 by the updated CustomerId
right_join(df2 %>%
mutate(CustomerId = as.character(customerId)) %>%
select(-customerId),
by = "CustomerId")
# View the result
df3
# CustomerId Product State
#1 987689 Toaster Alabama
#2 986581 <NA> Alabama
#3 7659090 Toaster Ohio
#4 56540 Radio Alabama
#5 74651 <NA> Alabama
#6 5168900 Radio Ohiohttps://stackoverflow.com/questions/45071639
复制相似问题