在R中查找相似命名向量(例如.*u pre和.*u post)之间的差异
我有一个带有多列的数据框,它在多个时间点上编码一个曝光(作为1/0),并遵循命名模式,例如exposure1\u pre2、exposure1\u pre1、exposure1\u post。。。曝光前2 工作示例在R中查找相似命名向量(例如.*u pre和.*u post)之间的差异,r,R,我有一个带有多列的数据框,它在多个时间点上编码一个曝光(作为1/0),并遵循命名模式,例如exposure1\u pre2、exposure1\u pre1、exposure1\u post。。。曝光前2 工作示例 library(dplyr) df <- tibble(exposure1_pre2 = sample(c(0, 1), size = 20, replace = T), exposure1_pre1 = sample(c(0, 1), size =
library(dplyr)
df <- tibble(exposure1_pre2 = sample(c(0, 1), size = 20, replace = T),
exposure1_pre1 = sample(c(0, 1), size = 20, replace = T),
exposure1_post = sample(c(0, 1), size = 20, replace = T),
exposure2_pre2 = sample(c(0, 1), size = 20, replace = T),
exposure2_pre1 = sample(c(0, 1), size = 20, replace = T),
exposure2_post = sample(c(0, 1), size = 20, replace = T)
)
很明显,我不知道如何构造条件,以便它寻找类似命名的*_pre2变量来评估差异,并且只需要从输入列中获取曝光部分来命名新列-我想grep可以在这里做什么
非常感谢你,祝你今天愉快 在“pre2”列上循环
,获取列名(cur_column()
),将子字符串替换为“pre1”,获取值,执行复合逻辑表达式,并使用+
强制将输出逻辑转换为二进制(或作为.integer
)
-输出
# A tibble: 20 x 8
exposure1_pre2 exposure1_pre1 exposure1_post exposure2_pre2 exposure2_pre1 exposure2_post exposure1_pre2_to_pre1 exposure2_pre2_to_pre1
<dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <int> <int>
1 1 0 1 0 1 1 0 1
2 1 0 1 1 0 0 0 0
3 1 0 1 1 0 0 0 0
4 1 1 1 0 1 0 0 1
5 0 1 1 0 0 0 1 0
6 1 1 1 0 1 1 0 1
7 0 1 0 1 0 0 1 0
8 0 1 0 1 1 1 1 0
9 0 1 0 0 1 0 1 1
10 1 0 1 1 1 0 0 0
11 0 0 1 0 0 1 0 0
12 0 1 1 1 1 1 1 0
13 0 1 1 1 1 0 1 0
14 1 1 1 0 0 1 0 0
15 1 1 1 1 0 0 0 0
16 1 1 1 0 0 1 0 0
17 0 0 0 1 0 0 0 0
18 1 0 0 0 0 0 0 0
19 1 0 0 0 0 1 0 0
20 1 0 1 1 0 1 0 0
#一个tible:20x8
曝光1_前2曝光1_前1曝光1_后曝光2_前2曝光2_前1曝光2_后曝光1_前2_至_前1曝光2_前2_至_前1曝光
1 1 0 1 0 1 1 0 1
2 1 0 1 1 0 0 0 0
3 1 0 1 1 0 0 0 0
4 1 1 1 0 1 0 0 1
5 0 1 1 0 0 0 1 0
6 1 1 1 0 1 1 0 1
7 0 1 0 1 0 0 1 0
8 0 1 0 1 1 1 1 0
9 0 1 0 0 1 0 1 1
10 1 0 1 1 1 0 0 0
11 0 0 1 0 0 1 0 0
12 0 1 1 1 1 1 1 0
13 0 1 1 1 1 0 1 0
14 1 1 1 0 0 1 0 0
15 1 1 1 1 0 0 0 0
16 1 1 1 0 0 1 0 0
17 0 0 0 1 0 0 0 0
18 1 0 0 0 0 0 0 0
19 1 0 0 0 0 1 0 0
20 1 0 1 1 0 1 0 0
这是故意的,但我同意,我删除了peri部分-谢谢!
library(dplyr)
library(stringr)
df %>%
mutate(
across(contains("pre2"),
~ +(. == 0 & get(str_replace(cur_column(), 'pre2', 'pre1')) == 1),
.names = '{.col}_to_pre1'))
# A tibble: 20 x 8
exposure1_pre2 exposure1_pre1 exposure1_post exposure2_pre2 exposure2_pre1 exposure2_post exposure1_pre2_to_pre1 exposure2_pre2_to_pre1
<dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <int> <int>
1 1 0 1 0 1 1 0 1
2 1 0 1 1 0 0 0 0
3 1 0 1 1 0 0 0 0
4 1 1 1 0 1 0 0 1
5 0 1 1 0 0 0 1 0
6 1 1 1 0 1 1 0 1
7 0 1 0 1 0 0 1 0
8 0 1 0 1 1 1 1 0
9 0 1 0 0 1 0 1 1
10 1 0 1 1 1 0 0 0
11 0 0 1 0 0 1 0 0
12 0 1 1 1 1 1 1 0
13 0 1 1 1 1 0 1 0
14 1 1 1 0 0 1 0 0
15 1 1 1 1 0 0 0 0
16 1 1 1 0 0 1 0 0
17 0 0 0 1 0 0 0 0
18 1 0 0 0 0 0 0 0
19 1 0 0 0 0 1 0 0
20 1 0 1 1 0 1 0 0