How can I split a character string in a dataframe into multiple columns

后端 未结 2 342
时光取名叫无心
时光取名叫无心 2021-01-23 05:38

I\'m working with a dataframe, one column of which contains values that are mostly numeric but may contain non-numeric entries. I would like to split this column into multiple

相关标签:
2条回答
  • 2021-01-23 06:21

    This does not use any packages:

    transform(df,
      x1 = ifelse(grepl(" ", x), sub(" .*", "", x), NA),
      x2 = sub(".* ", "", paste(x)))
    

    giving:

      ID     x   x1  x2
    1  1 < 0.1    < 0.1
    2  2   100 <NA> 100
    3  3 A 2.5    A 2.5
    4  4   200 <NA> 200
    
    0 讨论(0)
  • 2021-01-23 06:41

    You can use separate() from tidyr

    tidyr::separate(df, x, c("x1", "x2"), " ", fill = "left")
    #   ID   x1  x2
    # 1  1    < 0.1
    # 2  2 <NA> 100
    # 3  3    A 2.5
    # 4  4 <NA> 200
    

    If you absolutely need to remove the NA values, then you can do

    tdy <- tidyr::separate(df, x, c("x1", "x2"), " ", fill = "left")
    tdy[is.na(tdy)] <- ""
    

    and then we have

    tdy
    #   ID x1  x2
    # 1  1  < 0.1
    # 2  2    100
    # 3  3  A 2.5
    # 4  4    200
    
    0 讨论(0)
提交回复
热议问题