Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R - Split one column into two when the divider is a dot

Tags:

r

I am trying to split a column into two separate ones when the divider is a dot.

Following this example, I have tried first:

library(tidyverse)

df1 <- data.frame(Sequence.Name= c(2.1, 2.1, 2.1),
                  var1 = c(1, 1, 0))
df1$Sequence.Name %>% 
  as.character %>%
  str_split_fixed(".",2) %>%
  head
#>      [,1] [,2]
#> [1,] ""   ".1"
#> [2,] ""   ".1"
#> [3,] ""   ".1"

Created on 2021-04-05 by the reprex package (v0.3.0)

But this is not what I want: the first column is empty, and the second one has still the dot.

Following the comments in the post I linked above, I tried to add fixed="." or fixed=TRUE, but it does not seem to work:

library(tidyverse)

df1 <- data.frame(Sequence.Name= c(2.1, 2.1, 2.1),
                  var1 = c(1, 1, 0))
df1$Sequence.Name %>% 
  as.character %>%
  str_split_fixed(".",fixed=".",2) %>%
  head
#> Error in str_split_fixed(., ".", fixed = ".", 2): unused argument (fixed = ".")

Created on 2021-04-05 by the reprex package (v0.3.0)

like image 299
Emy Avatar asked Feb 28 '26 07:02

Emy


1 Answers

something like this?

df1 %>% separate(Sequence.Name, into = c("Col1", "Col2"))

  Col1 Col2 var1
1    2    1    1
2    2    1    1
3    2    1    0
like image 74
AnilGoyal Avatar answered Mar 02 '26 22:03

AnilGoyal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!