separating a value into columns

Hello Everyone,

I'm scraping a pdf.

Many of the variables are being imported as character vectors that comprise lists of numbers (see "have" in the script snippet), below.

I need to separate the numbers into separate variables and create a tibble (see "want" in the script snippet), below.

My thought is if I can replace the spaces with commas in "2.61 2.50 2.49 2.41 2.32", then I can use the commas to separate the numbers into individual variables.

I've attempted various approaches including:

  1. various stringer commands,
  2. tidyr::separate(), which returns the error: Error in UseMethod("separate_") : no applicable method for 'separate_' applied to an object of class "character".
  3. Converting to a tibble and using mutate.

So far, none of my ideas or searched-for solutions have resulted in converting what I have to what I want.

I'd appreciate any suggestions.

Thanks in advance


# What I have:
have <-   c("2.61 2.50 2.49 2.41 2.32")

# What I want:
want <- new_tibble(list(a = 2.61, b = 2.50, c = 2.49, d = 2.41, e =2.32))

How about this?

have <- c("2.61 2.50 2.49 2.41 2.32")

library(dplyr)
library(tidyr)

have %>% 
  as.data.frame() %>%  
  separate(1, into = c("a", "b", "c", "d", "e"), sep = " ") %>% 
  mutate_all(as.numeric)
#>      a    b    c    d    e
#> 1 2.61 2.50 2.49 2.41 2.32

Created on 2019-03-02 by the reprex package (v0.2.1)

3 Likes

@andresrcs, Thanks!

That worked like a charm.

I knew if would be something straightforward that i just wasn't seeing.

2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.