r - 同时修剪多个变量的因子标签
问题描述
这是我的玩具数据集:
library(tidyverse)
dat <- tibble (x1 = c("False - very long label specific to x1", "False - very long label specific to x1", "True - very long label specific to x1", "True - very long label specific to x1"),
x2 = c("False - very long label specific to x2", "False - very long label specific to x2", "False - very long label specific to x2", "True - very long label specific to x2"),
y = c(10, 5, 12, 4)) %>% mutate_at(vars(x1:x2), factor)
head(dat)
#> # A tibble: 4 x 3
#> x1 x2 y
#> <fct> <fct> <dbl>
#> 1 False - very long label specific~ False - very long label specific~ 10
#> 2 False - very long label specific~ False - very long label specific~ 5
#> 3 True - very long label specific ~ False - very long label specific~ 12
#> 4 True - very long label specific ~ True - very long label specific ~ 4
我想修剪很长的因子标签,它们都有两个共同点:
- 都以True或False开头
- 包括列名(即每列的因子标签是唯一的)
我想简化这一点,并且每个因子列只有True和False 之类的东西。这是我想要的输出:
#> # A tibble: 4 x 3
#> x1 x2 y
#> <fct> <fct> <dbl>
#> 1 False False 10
#> 2 False False 5
#> 3 True False 12
#> 4 True True 4
我认为它应该与类似mutate_at
andfct_relabel
和可能的东西一起使用str_trunc
,但我无法弄清楚。
解决方案
我们可以trimws
使用whitespace
library(dplyr)
dat %>%
mutate_if(is.factor, ~ factor(trimws(., whitespace = "\\s*-.*")))
# A tibble: 4 x 3
# x1 x2 y
# <fct> <fct> <dbl>
#1 False False 10
#2 False False 5
#3 True False 12
#4 True True 4
或fct_relabel
与str_remove
library(forcats)
library(stringr)
dat %>%
mutate_if(is.factor, ~ fct_relabel(., ~str_remove(., '\\s*-.*')))
或使用data.table
library(data.table)
m1 <- names(which(sapply(dat, is.factor)))
setDT(dat)[, (nm1) := lapply(.SD, function(x)
factor(sub('\\s*-.*', "", x))) , .SDcols = nm1]
推荐阅读
- php - 你能告诉我这个表格在做什么吗?
- python - 如何在python中自动创建票证
- c# - Parallel.ForEach(...) 的 CPU 使用率低
- sql - 如何解决别名中的此 SQL 查询标识符错误?
- java - DAO 设计用于更新数据库中的实体
- if-statement - 跳跃后返回
- android - 在 Android 中使用 MediaRecorder 记录整个屏幕并适合任何手机分辨率
- docker - 测试服务器拒绝 Meraki API 连接
- crash - Minecraft Foge 崩溃:java.lang.ArrayIndexOutOfBoundsException:0
- javascript - 点击动画缩放