type sex eth a_t a_tm b_tm c_tm d_tm e_tm
1 m a 0 0 0 1 1 0
0 f b 1 1 0 0 1 1
0 m a 0 0 0 1 1 1
1 f a 1 1 1 1 0 0
0 f c 1 0 0 1 0 1
如何使用dplyr列結尾處_tm或列在包含sex或的串列中選擇列eth?
預期產出
sex eth a_tm b_tm c_tm d_tm e_tm
m a 0 0 1 1 0
f b 1 0 0 1 1
m a 0 0 1 1 1
f a 1 1 1 0 0
f c 0 0 1 0 1
我想在dplyr不使用的情況下做到這一點grepl......這可能嗎?
uj5u.com熱心網友回復:
可以使用select-helpers- ends_within來完成select
library(dplyr)
df1 %>%
select(sex, eth, ends_with('_tm'))
-輸出
sex eth a_tm b_tm c_tm d_tm e_tm
1 m a 0 0 1 1 0
2 f b 1 0 0 1 1
3 m a 0 0 1 1 1
4 f a 1 1 1 0 0
5 f c 0 0 1 0 1
其他選項包括matches("_tm$")代替ends_with ie,如果我們使用regex,則可以全部完成matches-matches("^(sex|eth)$|_tm$")我們使用模式來匹配|從字串的開頭 ( ^) 到結尾 ( $)的 'sex' 或 ( ) 'eth'或( |)$列名中字串末尾( ) 的子字串 '_tm'
df1 %>%
select(matches("^(sex|eth)$|_tm$"))
sex eth a_tm b_tm c_tm d_tm e_tm
1 m a 0 0 1 1 0
2 f b 1 0 0 1 1
3 m a 0 0 1 1 1
4 f a 1 1 1 0 0
5 f c 0 0 1 0 1
資料
df1 <- structure(list(type = c(1L, 0L, 0L, 1L, 0L), sex = c("m", "f",
"m", "f", "f"), eth = c("a", "b", "a", "a", "c"), a_t = c(0L,
1L, 0L, 1L, 1L), a_tm = c(0L, 1L, 0L, 1L, 0L), b_tm = c(0L, 0L,
0L, 1L, 0L), c_tm = c(1L, 0L, 1L, 1L, 1L), d_tm = c(1L, 1L, 1L,
0L, 0L), e_tm = c(0L, 1L, 1L, 0L, 1L)), class = "data.frame",
row.names = c(NA,
-5L))
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/389586.html
