Use gsub remove all string before first white space in R

前端 未结 3 1083
温柔的废话
温柔的废话 2020-11-30 14:09

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 appl         


        
相关标签:
3条回答
  • 2020-11-30 14:28

    If D is your data frame, try

    sub(".+? ", "", D$name)
    
    0 讨论(0)
  • 2020-11-30 14:28

    Let's say your data frame is called 'df'

    library(reshape2)    
    df$name = colsplit(df$name," ", names = c("chuck","name"))[,2]
    
    0 讨论(0)
  • 2020-11-30 14:31

    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.

    0 讨论(0)
提交回复
热议问题