gpt4 book ai didi

r - 在 R 中使用 dplyr 选择不以字符串开头的列

转载 作者:行者123 更新时间:2023-12-03 01:55:53 25 4
gpt4 key购买 nike

我想从我的小标题中选择以字母 R 结尾且不以字符串(“hc”)开头的列。例如,如果我有一个如下所示的数据框:

name  hc_1  hc_2  hc_3r  hc_4r  lw_1r  lw_2  lw_3r  lw_4   
Joe 1 2 3 2 1 5 2 2
Barb 5 4 3 3 2 3 3 1

为了做我想做的事,我尝试了很多选择,但令我惊讶的是这个不起作用:

library(tidyverse)
data %>%
select(ends_with("r"), !starts_with("hc"))

当我尝试时,我收到此错误:

Error: !starts_with("hc") must evaluate to column positions or names, not a logical vector

我也尝试过使用 negate() 并得到相同的错误。

library(tidyverse)
data %>%
select(ends_with("r"), negate(starts_with("hc")))

Error: negate(starts_with("hc")) must evaluate to column positions or names, not a function

我想将答案保留在 dplyr select 函数中,因为一旦我选择了变量,我最终将使用 mutate_at 来反转它们,所以一个整洁的解决方案是最好的。

谢谢!

最佳答案

我们可以使用-,因为starts_with输出不是逻辑向量

library(dplyr)
data %>%
select(ends_with("r"), -starts_with("hc"))
# lw_1r lw_3r
#1 1 2
#2 2 3

数据

data <- structure(list(name = c("Joe", "Barb"), hc_1 = c(1L, 5L), hc_2 = c(2L, 
4L), hc_3r = c(3L, 3L), hc_4r = 2:3, lw_1r = 1:2, lw_2 = c(5L,
3L), lw_3r = 2:3, lw_4 = 2:1), class = "data.frame", row.names = c(NA,
-2L))

关于r - 在 R 中使用 dplyr 选择不以字符串开头的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57730736/

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