我有一个两个变量的数据帧,其中一个是字符向量。"MyVector" 中的每一行都包含一个只有一个名字的字符串(即“Pete”)。名称在字符串中的位置可能会有所不同。我想创建将列表中的名称与字符串中的名称匹配的代码,并将该名称提取到数据框中的新变量中。如果名称始终位于向量“MyVector”中的相同位置,我将创建一个新变量作为 MyVector 的子字符串,将名称提取到新列中。我从 Stringr 尝试了各种版本的 str_detect 无济于事。
挑战:如果名称位于多个位置,我如何检测名称或将名称提取到新变量中并将其放入 MyDF?
#Create the data frame
var.1 <-rep(c(1,5,3),2)
MyVector <- c("I know Pete", "Jerry has a new job","Victor is an employee","How to work with Pete","Too Many Students","Bob is mean")
MyDF <-as.data.frame(cbind(var.1,MyVector))
#Create a vector of a list of names I want to extract into a new column in the dataframe.
Extract <- c("Jerry","Pete", "Bob", "Victor")
#Match would be perfect if I could use it on character vectors
MyDF$newvar <-match(MyDF$MyVector,Extract)
Run Code Online (Sandbox Code Playgroud)
我的最终 data.frame 应该类似于下面的输出。
var.1 MyVector NEWVAR
1 1 Don knows Pete Pete
2 5 Jerry has a new job Jerry
3 3 Victor and Bob are employees Victor
4 1 How to work with Pete Pete
5 5 Too Many Students NA
6 3 Bob is mean Bob
Run Code Online (Sandbox Code Playgroud)
我们可以使用str_extract后,paste荷兰国际集团的“精华”在一起
library(stringr)
MyDF$NEWVAR <- str_extract(MyDF$MyVector, paste(Extract, collapse="|"))
MyDF$NEWVAR
#[1] "Pete" "Jerry" "Victor" "Pete" NA "Bob"
Run Code Online (Sandbox Code Playgroud)