Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use gsub remove all string before first white space in R

Tags:

regex

r

gsub

I have a data frame like this:

name         weight
r apple         0.5
y pear          0.4
y cherry        0.1
g watermelon    5.0
pp grape        0.5
y apple pear    0.4
...  ...

I would like to remove all characters before the first white space in the name column. Can anybody give me a favor? Thank you!

like image 829
cutebunny Avatar asked Sep 24 '15 17:09

cutebunny


People also ask

How do I remove white spaces from a string in R?

gsub() function is used to remove the space by removing the space in the given string.

How do I remove GSUB from R?

To remove a character in an R data frame column, we can use gsub function which will replace the character with blank. For example, if we have a data frame called df that contains a character column say x which has a character ID in each value then it can be removed by using the command gsub("ID","",as.

How do I remove a string in R?

How to remove a character or multiple characters from a string in R? You can either use R base function gsub() or use str_replace() from stringr package to remove characters from a string or text.

How do I remove the first word from a string in R?

To remove the string's first character, we can use the built-in substring() function in R. The substring() function accepts 3 arguments, the first one is a string, the second is start position, third is end position.


1 Answers

Try this:

sub(".*? ", "", D$name)

Edit:

The pattern is looking for any character zero or more times (.*) up until the first space, and then capturing the one or more characters ((.+)) after that first space. The ? after .* makes it "lazy" rather than "greedy" and is what makes it stop at the first space found. So, the .*? matches everything before the first space, the space matches the first space found.

like image 108
Jota Avatar answered Sep 17 '22 08:09

Jota