gpt4 book ai didi

r dplyr ends_with多个字符串匹配

转载 作者:行者123 更新时间:2023-12-03 16:06:51 25 4
gpt4 key购买 nike

我可以使用dplyr::select(ends_with)选择适合多个条件中的任何一个的列名称。考虑到我的列名,我想使用结尾于而不是包含或匹配项,因为我要选择的字符串与列名的末尾相关,但也可能出现在其他中间。例如,

df <- data.frame(a10 = 1:4,
a11 = 5:8,
a20 = 1:4,
a12 = 5:8)

我想选择以1或2结尾的列,以仅具有a11和a12列。 select(ends_with)是执行此操作的最佳方法吗?

谢谢!

最佳答案

您也可以使用正则表达式执行此操作。我知道您最初不想使用匹配项,但是如果您使用“字符串结尾”符号$,它实际上会很好地工作。用|分隔各种结尾。

df <- data.frame(a10 = 1:4,
a11 = 5:8,
a20 = 1:4,
a12 = 5:8)

df %>% select(matches('1$|2$'))
a11 a12
1 5 5
2 6 6
3 7 7
4 8 8

如果您的 list 比较复杂,请使用 paste0collapse = '|'
dff <- data.frame(a11 = 1:3,
a12 = 2:4,
a13 = 3:5,
a16 = 5:7,
my_cat = LETTERS[1:3],
my_dog = LETTERS[5:7],
my_snake = LETTERS[9:11])

my_cols <- paste0(c(1,2,6,'dog','cat'),
'$',
collapse = '|')

dff %>% select(matches(my_cols))

a11 a12 a16 my_cat my_dog
1 1 2 5 A E
2 2 3 6 B F
3 3 4 7 C G

关于r dplyr ends_with多个字符串匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45714741/

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