我有一个数据集,例如:
dat1 <- read.table(header=TRUE, text="
Trust_01_T1 Trust_02_T1 Trust_03_T1 Trust_01_T2 Trust_02_T2 Trust_03_T2 Cont_01_T1 Cont_01_T2
5 1 2 1 5 3 1 1
3 1 3 3 4 2 1 2
2 1 3 1 3 1 2 2
4 2 5 5 3 2 3 3
5 1 4 1 2 2 4 5
")
我想使用select函数来收集包含Trust AND T1的变量。
dat1 <- dat1 %>%
mutate(Trust_T1 = select(., contains("Trust")))
有人知道如何使用两个Arguments来获得Trust AND T1吗。如果我使用:
dat1 <- dat1 %>%
mutate(Trust_T1 = select(., contains("Trust"), contains("T1")))
它给了我包含Trust或T1的变量。
最好!
如果我们需要两者,那么使用带有正则表达式的matches
来指定以"Trust"开头(^
(、以"T1"结尾($
(的列名(假设这些只是模式
library(dplyr)
dat1 %>%
select(matches("^Trust_.*T1$"))
用于创建新列的mutate
不清楚,因为有多个列与后面跟着"T1"的"信任"匹配。如果打算对所选列进行一些操作,则可以是across
或c_across
和rowwise
(从帖子中不清楚(
一种解决方案可能是:
library(dplyr)
df %>% select(starts_with('Trust') | contains('_T1'))
#> Trust_01_T1 Trust_02_T1 Trust_03_T1 Trust_01_T2 Trust_02_T2 Trust_03_T2
#> 1 5 1 2 1 5 3
#> 2 3 1 3 3 4 2
#> 3 2 1 3 1 3 1
#> 4 4 2 5 5 3 2
#> 5 5 1 4 1 2 2
#> Cont_01_T1
#> 1 1
#> 2 1
#> 3 2
#> 4 3
#> 5 4
数据
df <- read.table(text =
"
Trust_01_T1 Trust_02_T1 Trust_03_T1 Trust_01_T2 Trust_02_T2 Trust_03_T2 Cont_01_T1 Cont_01_T2
5 1 2 1 5 3 1 1
3 1 3 3 4 2 1 2
2 1 3 1 3 1 2 2
4 2 5 5 3 2 3 3
5 1 4 1 2 2 4 5
", header =T)