所以我有一个密码数据集,如果密码与以下字符串之一匹配,我想创建一个新列(我正在使用 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/