R语言:查找字符列表中含特定字符串元素的位置
Got it, let's fix this for you! The issue with match() and str_locate() is that they don't do what you need here:
match()looks for exact matches of your target string (it would only find an element that's exactly "Belgium", which doesn't exist in your list)str_locate()returns the position of the string inside each element, not the index of the element in the list
Instead, use grep()—it's designed to find elements in a character vector that contain a specific substring, and returns their indices directly.
Step 1: Define the Function
Here's a simple function that takes your character list and target string, then returns the position(s) of elements containing that string:
find_element_position <- function(char_list, target) { # grep returns indices of elements that contain the target substring grep(target, char_list) }
Step 2: Test It with Your Data
Using your list_April example:
# Test with "Belgium" find_element_position(list_April, "Belgium") # Output: [1] 7 # Test another country, like "United States" find_element_position(list_April, "United States") # Output: [1] 19
Alternative: Using grepl() + which()
If you prefer a more explicit approach, you can combine grepl() (which returns a logical vector indicating matches) with which() (which converts logicals to indices):
find_element_position <- function(char_list, target) { which(grepl(target, char_list)) }
This works exactly the same way as the grep version—just a different syntax.
Why Your Previous Attempts Didn't Work
match("Belgium", list_April)returnsNAbecause none of the elements are exactly "Belgium" (all have extra numbers/text)str_locate(list_April, "Belgium")returns a matrix showing where "Belgium" starts/ends in each element, not the element's position in the list
内容的提问来源于stack exchange,提问作者Anthony Martin

