R-基于部分字符串创建新列 [英] R - Creating New Column Based off of a Partial String
问题描述
我有一个大型数据集(数据集 A),其中有一个列说明
,其中包含类似于
1952 Rolls Royce Silver Wraith或 1966 Holden 。
I have a large dataset (Dataset "A") with a column Description
which contains something along the lines
"1952 Rolls Royce Silver Wraith" or "1966 Holden".
我还有一个单独的数据集(数据集 B),其中列出了我需要的每个汽车品牌
(例如 保持, 劳斯莱斯,保时捷)。
I also have a separate dataset (Dataset "B") with a list of every Car Brand
that I need (eg "Holden", "Rolls Royce", "Porsche").
如何创建数据集 A中的新列为说明
的部分字符串分配了正确的汽车品牌
?
How can I create a new column in dataset "A" that assigns the Partial strings of the Description
with the correct Car Brand
?
(此列仅包含具有相应匹配单元格的正确 Car Brand
)。
(This column would only hold the correct Car Brand
with the appropriate matching cell).
谢谢。
说明新列
1971 Austin 1300 Austin
推荐答案
tidyverse的解决方案
A solution from the tidyverse
A <- data.frame (Description = c("1970 Austin"),
stringsAsFactors = FALSE)
B <- data.frame (Car_Brand = c("Austin"),
stringsAsFactors = FALSE)
library(tidyverse)
A %>% mutate( New_Column= str_match( Description, B$Car_Brand)[,1] )
# Description New_Column
# 1 1970 Austin Austin
这篇关于R-基于部分字符串创建新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!