Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
218 views
in Technique[技术] by (71.8m points)

r - Select only the first two digits of a string of the value that starts with a letter and do nothing otherwise

how can I select only the first two digits of a string of the value that starts with a letter and do nothing otherwise?

Value = I240 G460 1560 S50

I would like to get:

Value = I24 G46 1560 S50

So far I am trying:

df <- df %>% mutate(Value = ifelse(str_detect(Value, '[A-Z]'~'\d{2}')))
question from:https://stackoverflow.com/questions/65941088/select-only-the-first-two-digits-of-a-string-of-the-value-that-starts-with-a-let

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here's a hack solution - there is likely a better way:

library(dplyr)

df <- data.frame(Value = c("I240", "G460", "1560", "S50"))

df %>% 
  mutate(temp = substr(Value,1,1),
         temp = is.na(as.numeric(as.character(temp))),
         Value = ifelse(temp == TRUE, substr(Value,1,3), Value)) %>% 
  select(-temp)

This gives us:

 Value
1   I24
2   G46
3  1560
4   S50

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...