【发布时间】:2020-03-10 03:13:18
【问题描述】:
我有一个数据集,其中包含汽车品牌名称和其他数据 (test1),以及一个包含所有唯一缩短的汽车品牌名称的向量 (test)。
test<-c("Rolls Royce", "Toyota", "Tesla", "BMW","Ford", "Mercedes")
test1<- data.frame(Brand = c("Mercedes Benz", "Bayerische Motoren Werke (BMW)",
"Ford Motor Corp.", "Rolls Royce",
"Tesla", "Mercedes Benz", "Ford Motor"),
Ratings = c(6,6,4,9,8,8,6))
如何使用唯一汽车名称的字符串向量 (test) 对数据集 (test1) 进行部分字符串匹配并更改 的 Brand 值>test1 来搜索和匹配 test 的值?
我可以为每个条目都这样做,但我想看看是否有更快的方法来获得结果:
library(data.table)
test1[test1$Brand %like% "Rolls Royce", ]$Brand <-"Rolls Royce"
test1[test1$Brand %like% "Toyota", ]$Brand <-"Toyota"
test1[test1$Brand %like% "Tesla", ]$Brand <-"Tesla"
test1[test1$Brand %like% "BMW", ]$Brand <-"BMW"
test1[test1$Brand %like% "Ford", ]$Brand <-"Ford"
test1[test1$Brand %like% "Mercedes", ]$Brand <-"Mercedes"
这是我想为上述示例获得的结果:
data.frame(Brand = c("Mercedes", "BMW",
"Ford", "Rolls Royce",
"Tesla", "Mercedes", "Ford"),
Ratings = c(6,6,4,9,8,8,6))
【问题讨论】: