Remove all characters in a string after a “.” in R

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP


Remove all characters in a string after a “.” in R



I have a group of strings in a column like this

Group1
Group1.1
Group1.2
Group1.3



Group1
Group1.1
Group1.2
Group1.3



I want to remove all characters after the decimal point so it looks like this



Group1
Group1
Group1


Group1
Group1
Group1



How do I do this in R code? Thank you




2 Answers
2



We can use sub to match the dot (\. - escape it as it is a metacharacter specifying any character) followed by other characters (.*) until the end ($) of the string and replace it with blank ("")


sub


\.


.*


$


""


df1$Col <- sub("\..*$", "", df1$Col)
df1$Col
#[1] "Group1" "Group1" "Group1" "Group1"


df1 <- structure(list(Col = c("Group1", "Group1.1", "Group1.2", "Group1.3"
)), .Names = "Col", class = "data.frame", row.names = c(NA, -4L
))





so .* matches everything after . until the end and replace it?
– YOLO
26 mins ago


.*


.





Worked perfectly! Thank you :)
– Umber Sheikh
26 mins ago





@YOLO Yes, it would be zero or more characters after the escaped dot
– akrun
25 mins ago



Following may also help you here.


sub("([^\.]*)\..*","\1",df1$Col)



Output will be as follows.


[1] "Group1" "Group1" "Group1" "Group1"



test Data is:


df1 <- structure(list(Col = c("Group1", "Group1.1", "Group1.2", "Group1.3"
)), .Names = "Col", class = "data.frame", row.names = c(NA, -4L
))



Explanation: Adding explanation of above code(only for explanation purposes).


sub( ##Using sub function of R here.
"([^\.]*) ##BY mentioning () means creating a place in memory to hold the matched regex's value, in here it will be from starting to till DOT comes.
\..*", ##Now mentioning DOT \ is for escaping the DOT to be meant from its special value and .* means till end of the value of data frame.
"\1", ##replace the complete value of data frame with first memory place which will be value before DOT.
df1$Col) ##Mentioning dataframe df1's col value here.






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Arduino Mega cannot recieve any sketches, stk500_recv() programmer is not responding

Visual Studio Code: How to configure includePath for better IntelliSense results

Future solutions