gpt4 book ai didi

r - 将两个数据框与字符串中具有特定模式的列合并

转载 作者:行者123 更新时间:2023-12-02 04:17:56 27 4
gpt4 key购买 nike

(过去两天我一直被这个问题困扰,所以如果它有答案,请耐心等待。)

我有两个数据框 A 和 B。我想将它们合并到“名称”列上。假设 A 有两列“名称”和“编号”。 A df 的“名称”列的值为“.tony.x.rds”、“.tom.x.rds”等。

Name     Numbers
.tony.x.rds 15.6
.tom.x.rds 14.5

B df 有两列 Name 和 ChaR。 B 的“名称”列的值为“tony.x”、“tom.x”等。

Name  ChaR
tony.x ENG
tom.x US

两个 dfs 的 Name 列中的主要元素是“tony”、“tom”等。

So, ".tony.x.rds" is equal to "tony.x" and ".tom.x.rds" is equal to "tom.x".

我尝试过使用各种选项的 gsub,在 A 和 B 数据框的名称列中留下“tony”、“tom”等。但是当我使用时

StoRe<-merge(A,B, all=T)

我获取 A 和 B 的所有行而不是单行。也就是说,每个“a”、“b”等有两行,在 Numbers 和 ChaR 列中具有各自的值。例如:

Name Numbers ChaR
tony 15.6 NA
tony NULL ENG
tom 14.5 NA
tom NULL US

这让我头疼欲裂。我请求你帮忙。

最佳答案

一种可能的解决方案。我不完全确定您想对字符串中的“x”做什么,我已将它们保留在链接键中,但是通过将 \\1\\2 更改为 \\1 你只保留第一个字母。

a <- data.frame(
Name = paste0(".", c("tony", "tom", "foo", "bar", "foobar"), ".x.rds"),
Numbers = rnorm(5)
)

b <- data.frame(
Name = paste0(c("tony", "tom", "bar", "foobar", "company"), ".x"),
ChaR = LETTERS[11:15]
)

# String consists of 'point letter1 point letter2 point rds'; replace by
# 'letter1 letter2'
a$Name_stand <- gsub("^\\.([a-z]+)\\.([a-z]+)\\.rds$", "\\1\\2", a$Name)

# String consists of 'letter1 point letter2'; replace by 'letter1 letter2'
b$Name_stand <- gsub("^([a-z]+)\\.([a-z]+)$", "\\1\\2", b$Name)

result <- merge(a, b, all = TRUE, by = "Name_stand")

输出:

#> result
# Name_stand Name.x Numbers Name.y ChaR
#1 barx .bar.x.rds 1.38072696 bar.x M
#2 companyx <NA> NA company.x O
#3 foobarx .foobar.x.rds -1.53076596 foobar.x N
#4 foox .foo.x.rds 1.40829287 <NA> <NA>
#5 tomx .tom.x.rds -0.01204651 tom.x L
#6 tonyx .tony.x.rds 0.34159406 tony.x K

另一个,也许更健壮(对于字符串的变体,如“tom.rds”和“tom”,它们仍然会被链接;这当然也可能是一个缺点)/

# Remove the rds from a$Name
a$Name_stand <- gsub("rds$" , "", a$Name)
# Remove all non alpha numeric characters from the strings
a$Name_stand <- gsub("[^[:alnum:]]", "", a$Name_stand)
b$Name_stand <- gsub("[^[:alnum:]]", "", b$Name)

result2 <- merge(a, b, all = TRUE, by = "Name_stand")

关于r - 将两个数据框与字符串中具有特定模式的列合并,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40253821/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com