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!
gsub() function is used to remove the space by removing the space in the given string.
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 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.
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.
Try this:
sub(".*? ", "", D$name)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With