How to test if the first three characters in a string are letters or numbers in r?

落花浮王杯 提交于 2019-12-08 05:09:28

I would try:

x <- substr(dt$X, 1, 3)
dt$X <- ifelse(grepl('[0-9]', x), 'FR', x)
dt
#   ID   X
# 1  1 MJF
# 2  2  FR
# 3  3 DEW
# 4  4  FR
# 5  5 DAS

The data:

structure(list(ID = 1:5, X = c("MJF34", "GA249D", "DEW235R", 
"4SDFR3", "DAS3")), .Names = c("ID", "X"), class = "data.frame", 
row.names = c(NA, 
-5L))

You can use standard base R commands

# Your data, dt$X in your case
x = c("MJF34", "GA249D", "DEW235R", "4SDFR3", "DAS3")

First use substr to extract characters 1 to 3

sub_str = substr(x, 1, 3)

Then test for a number

has_numbers = grep("[0-9]", sub_str)

Then replace

sub_str[has_numbers] = "FR"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!