R - Creating New Column Based off of a Partial String

折月煮酒 提交于 2019-12-13 09:49:14

问题


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".

I also have a separate dataset (Dataset "B") with a list of every Car Brand that I need (eg "Holden", "Rolls Royce", "Porsche").

How can I create a new column in dataset "A" that assigns the Partial strings of the Description with the correct Car Brand?

(This column would only hold the correct Car Brand with the appropriate matching cell).

Thank you.

Description New Column 1971 Austin 1300 Austin


回答1:


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


来源:https://stackoverflow.com/questions/52618671/r-creating-new-column-based-off-of-a-partial-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!