是否有可以替换包含某些字符的数据的 R 函数?
Is there an R function that can replace data that contains certain characters?
我的是这样的:
Contact
ID Number
Me@email
576489
You@memail
984601
072233498
256470
@email
---
我想替换它,以便将包含 @ 或数字的任何内容完全替换为简单的“是”,这可能吗?所以它会输出这样的东西:
Contact
ID Number
Yes
Yes
Yes
Yes
Yes
Yes
Yes
---
str_replace(字符串、模式、替换)来自包“stringr”
str_replace(string, "@", "Yes")
你可以这样做:
df[] <- lapply(df, function(x) ifelse(grepl("@|\d", x), "Yes", x))
df
#> Contact ID Number
#> 1 Yes Yes
#> 2 Yes Yes
#> 3 Yes Yes
#> 4 Yes ---
可重现数据
df <- structure(list(Contact = c("Me@email", "You@memail", "072233498",
"@email"), `ID Number` = c("576489", "984601", "256470", "---"
)), class = "data.frame", row.names = c(NA, -4L))
df
#> Contact ID Number
#> 1 Me@email 576489
#> 2 You@memail 984601
#> 3 072233498 256470
#> 4 @email ---
我的是这样的:
Contact | ID Number |
---|---|
Me@email | 576489 |
You@memail | 984601 |
072233498 | 256470 |
--- |
我想替换它,以便将包含 @ 或数字的任何内容完全替换为简单的“是”,这可能吗?所以它会输出这样的东西:
Contact | ID Number |
---|---|
Yes | Yes |
Yes | Yes |
Yes | Yes |
Yes | --- |
str_replace(字符串、模式、替换)来自包“stringr”
str_replace(string, "@", "Yes")
你可以这样做:
df[] <- lapply(df, function(x) ifelse(grepl("@|\d", x), "Yes", x))
df
#> Contact ID Number
#> 1 Yes Yes
#> 2 Yes Yes
#> 3 Yes Yes
#> 4 Yes ---
可重现数据
df <- structure(list(Contact = c("Me@email", "You@memail", "072233498",
"@email"), `ID Number` = c("576489", "984601", "256470", "---"
)), class = "data.frame", row.names = c(NA, -4L))
df
#> Contact ID Number
#> 1 Me@email 576489
#> 2 You@memail 984601
#> 3 072233498 256470
#> 4 @email ---