r - 检测字符串的类型并相应地创建新变量

标签 r regex tidyverse

所以我有一个密码数据集,如果密码与以下字符串之一匹配,我想创建一个新列(我正在使用 R)

id password   year     lenght
1  1 12345      2001       5
2  2 pass4      2002       5
3  3 angel      2003       5
4  4 pizza      2004       5

仅包含字母的密码模式:“^[a-zA-Z]+$”

仅包含数字的密码模式:“^[0-9]*$”

同时包含数字和字母的密码模式:'([0-9].[a-zA-Z])|([a-zA-Z].[0-9] )'

所以基本上我需要一个名为:TYPE 的新列,具有 3 个级别(数字、字母或两者)

我需要的是这个:

id password   year     lenght   Type
1  1 12345      2001       5.   numbers only    
2  2 pass4      2002       5.   both
3  3 angel      2003       5.   letters only
4  4 pizza      2004       5.   letters only

最佳答案

您可以使用以下解决方案。请记住,我们将条件从最具体(两个)到最一般(其他两个条件之一):

library(dplyr)

df %>%
  mutate(Type = case_when(
    grepl("[A-Za-z]+", password) & grepl("[1-9]+", password) ~ "Both",
    grepl("[A-Za-z]+", password) ~ "Letters Only",
    grepl("[1-9]+", password) ~ "Numbers Only",
    TRUE ~ as.character(password)
  ))

  id password year lenght         Type
1  1    12345 2001      5 Numbers Only
2  2    pass4 2002      5         Both
3  3    angel 2003      5 Letters Only
4  4    pizza 2004      5 Letters Only

关于r - 检测字符串的类型并相应地创建新变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70139533/

相关文章:

r - 如何使用从 base::cut() 函数派生的轴减少 ggplot 的刻度数

R:以 hh:mm:ss 的形式添加超过 24 小时的时间/持续时间

regex - 如何使用 Regexp 检索链接文本在括号中有数字的 URL

r - 使用 `chisq.test()$p.value` 为多个组获取 `dplyr::group_by()`

r - 当使用带有多个变量的pivot_longer时,我丢失了常量变量(包括id)

r - 用相同数量的空格替换多个前导字符的 native 正则表达式方法

R将矩阵中的所有列与循环中的每个列进行比较

c# - 重复一个组的值与另一个组的值一样多的次数

regex - 如何通过正则表达式获取字符串的第一个匹配项?

r - R 中按字符串格式过滤