R:根据截止值对所有数值变量 (1:0) 进行分类

R: categorize all numeric variables (1:0) according to a cut-off

我有以下数据框:

structure(list(test1 = c(0.12, 0.2, 0.55, 0.22, 0.19, 0.17, 0.15, 
0.12, 0.32, 0.23, 0.32, 0.23), test2 = c(0.15, 0.12, 0.32, 0.23, 
0.12, 0.2, 0.55, 0.22, 0.12, 0.2, 0.55, 0.22), test3 = c(0.07, 
0.01, 0, 0.13, 0.16, 0.78, 0.98, 0.1, 0.5, 0.3, 0.4, 0.5), test4 = c(0.23, 
0.12, 0.2, 0.2, 0.55, 0.22, 0.12, 0.2, 0.55, 0.22, 0.55, 0.42
)), row.names = c(NA, -12L), class = c("tbl_df", "tbl", "data.frame"
))

我正在尝试编写一个脚本,为每个变量(test1、test2、test3...)创建(并添加到数据框)一个双变量(命名为 out_testX)取决于变量值是主要的还是等于 .20.

结果,应该是这样的:

structure(list(test1 = c(0.12, 0.2, 0.55, 0.22, 0.19, 0.17, 0.15, 
0.12, 0.32, 0.23, 0.32, 0.23), test2 = c(0.15, 0.12, 0.32, 0.23, 
0.12, 0.2, 0.55, 0.22, 0.12, 0.2, 0.55, 0.22), test3 = c(0.07, 
0.01, 0, 0.13, 0.16, 0.78, 0.98, 0.1, 0.5, 0.3, 0.4, 0.5), test4 = c(0.23, 
0.12, 0.2, 0.2, 0.55, 0.22, 0.12, 0.2, 0.55, 0.22, 0.55, 0.42
), out_test1 = c(0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1), out_test2 = c(0, 
0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1), out_test3 = c(0, 0, 0, 0, 0, 
1, 1, 0, 1, 1, 1, 1), out_test4 = c(1, 0, 1, 1, 1, 1, 0, 1, 1, 
1, 1, 1)), row.names = c(NA, -12L), class = c("tbl_df", "tbl", 
"data.frame"))

谁能帮帮我? 谢谢

mutate_all,我们通过list中的函数指定要添加到列名的后缀,如果需要作为前缀,请在rename_at中执行此操作

library(dplyr)
library(stringr)
df1 %>% 
     mutate_all( list(out = ~+( . >= .2))) %>%
     rename_at(vars(ends_with('out')), ~ str_replace(., '(.*)_(out)', '\2_\1'))

或使用base R

df1[paste0("out_", names(df1))] <- +(df1 >= .2)