基于同一数据中另一字符列内容在R语言中新增字符列
Hey there! Let's fix this problem for you. The issue with your initial attempts is that contains() is meant for selecting columns (not parsing text inside cells) and %in% checks if a value exists in a vector—neither helps extract specific text from strings. Instead, we'll pair dplyr::mutate() with string-handling tools from the stringr package (which works seamlessly with dplyr) to pull out the business names you need.
Step 1: Set Up Your Sample Data
First, let's recreate your dataset so you can test the code directly:
library(dplyr) library(stringr) # Your example dataset df <- tibble( A = c( "Apple Bees in the right area", "We love Apple Bees here", "Waffle House: the place to go! 5 stars", "Nothing better than Waffle House!" ) )
Step 2: Extract Business Names with str_extract()
We'll use str_extract() to pull the first matching business name from each string in column A. We can define a regex pattern that matches either "Apple Bees" or "Waffle House":
df <- df %>% mutate(F = str_extract(A, "Apple Bees|Waffle House"))
Step 3: (Optional) Scale for More Businesses
If you have a longer list of businesses, store them in a vector and dynamically build the regex pattern—this keeps your code clean and easy to update:
# List of businesses to match business_list <- c("Apple Bees", "Waffle House") # Build regex pattern (separate names with | for "or") match_pattern <- str_c(business_list, collapse = "|") df <- df %>% mutate(F = str_extract(A, match_pattern))
Result
When you run the code, your dataset will have the new column F with the exact business names you want:
print(df) #> # A tibble: 4 × 2 #> A F #> <chr> <chr> #> 1 Apple Bees in the right area Apple Bees #> 2 We love Apple Bees here Apple Bees #> 3 Waffle House: the place to go! 5 stars Waffle House #> 4 Nothing better than Waffle House! Waffle House
Why This Works
str_extract()searches each string in column A and returns the first substring that matches our regex pattern.- The
|in the pattern means "match either the text before or after this symbol". - This approach is flexible—add more business names to
business_listand the code will automatically match them without extra changes.
内容的提问来源于stack exchange,提问作者RocketPockets22

