jeremylindsell
jeremylindsell

Reputation: 23

Split multiple entries on basis of separator

I've got a vector that looks something like this:

df <- c("201/304", "445.5/553", "665/543/224", "332.0/433.0")

Multiple values have been entered into a cell with a hash separator. Some have two and some have three values (and some may have more). I'm looking for a general way to split this up to create vector with a single value in each (and no hashes).

I need something that will look like this:

df <- c(201, 304, 445.5, 553, 665, 543, 224, 332.0, 433)

I've tried strsplit() but then get stuck how to rearrange the output as I need it.

Upvotes: 2

Views: 91

Answers (3)

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193517

I don't see scan mentioned here yet, but the following should also work:

scan(text = df, sep = "/")
# Read 9 items
# [1] 201.0 304.0 445.5 553.0 665.0 543.0 224.0 332.0 433.0

Upvotes: 3

akrun
akrun

Reputation: 887088

We can use strsplit

as.numeric(unlist(strsplit(df, '[/]')))

Or use str_extract

library(stringr)
as.numeric(unlist(str_extract_all(df, '[^/]+')))

Upvotes: 3

polka
polka

Reputation: 1529

Use the following.

unlist(strsplit(df, split = "/"))

Upvotes: 0

Related Questions