gpt4 book ai didi

r - 基于字符串列表的子集使用 grepl()?

转载 作者:行者123 更新时间:2023-12-04 02:43:53 26 4
gpt4 key购买 nike

我正在做一些看似非常简单的事情。我想使用 grepl() 命令——或类似的命令——在几个不同的短语上对 R 中的数据帧进行子集化,而不构建循环。

例如,我想提取名为 Bob 或 Mary 的任何人的所有行:

## example data frame:
tmp = structure(list(Name = structure(c(6L, 8L, 9L, 7L, 2L, 3L, 10L,
1L, 5L, 4L), .Label = c("Alan", "Bob", "bob smith", "Frank",
"John", "Mary Anne", "mary jane", "Mary Smith", "Potter, Mary",
"smith, BOB"), class = "factor"), Age = c(31L, 23L, 23L, 55L,
32L, 36L, 45L, 12L, 43L, 46L), Height = 1:10), .Names = c("Name",
"Age", "Height"), class = "data.frame", row.names = c(NA, -10L
))

tmp

# Name Age Height
#1 Mary Anne 31 1
#2 Mary Smith 23 2
#3 Potter, Mary 23 3
#4 mary jane 55 4
#5 Bob 32 5
#6 bob smith 36 6
#7 smith, BOB 45 7
#8 Alan 12 8
#9 John 43 9
#10 Frank 46 10

## this doesn't work
mynames=c('bob','mary')
tmp[grepl(mynames,tmp$Name,ignore.case=T),]

任何想法都会有所帮助!

最佳答案

您可以结合您的 mynames带有正则表达式运算符的向量 |并使用 grep .

tmp[grep(paste(mynames, collapse='|'), tmp$Name, ignore.case=TRUE),]

# Name Age Height
# 1 Mary Anne 31 1
# 2 Mary Smith 23 2
# 3 Potter, Mary 23 3
# 4 mary jane 55 4
# 5 Bob 32 5
# 6 bob smith 36 6
# 7 smith, BOB 45 7

关于r - 基于字符串列表的子集使用 grepl()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14487877/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com