1

I'm trying to split a number with a decimal into 2 separate numbers (characters work as well).

a <- c(1241.3233, 5632.2344, 1313,8643)

I would like to return this

col1    col2
1241    3233
5632    2344
1313    8643

I've tried

strsplit(as.character(a), ".")

and

stringr::str_split(a,".")

with no success.

neilfws
  • 32,751
  • 5
  • 50
  • 63
ericbrownaustin
  • 1,230
  • 4
  • 18
  • 36

2 Answers2

4

Two points:

1) Coerce number to string using as.character

2) Escape the period using \\

a = c(1241.3233, 5632.2344, 1313.8643)
do.call(rbind, strsplit(as.character(a),"\\."))
#     [,1]   [,2]  
#[1,] "1241" "3233"
#[2,] "5632" "2344"
#[3,] "1313" "8643"
Rich Scriven
  • 97,041
  • 11
  • 181
  • 245
d.b
  • 32,245
  • 6
  • 36
  • 77
3

If you are working on a data frame, and your desired output is going to be a data frame. The separate function from tidyr could be useful. Here is an example.

library(tidyverse)

# Create example data frame
dt <- data.frame(a = c(1241.3233, 5632.2344, 1313.8643))

# Separate the column a into col1 and col2
dt2 <- dt %>%
  separate(a, into = c("col1", "col2"))
www
  • 38,575
  • 12
  • 48
  • 84