1

This is my current data set enter image description here

I want to take the numbers after "narrow" (e.g. 20) and make another vector. Any idea how I can do that?

ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
Lee Drown
  • 35
  • 2
  • 6
  • 1
    It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. Do not post data as images -- this is not easily reproducible. – MrFlick Feb 18 '20 at 20:13
  • You could try something along the lines of strsplit(data[,1],","). You'll have better luck getting an answer with reproducible data. – Daniel O Feb 18 '20 at 20:14
  • when working with data.table-format: `data.table::tstrsplit( Stimulus, ",")` will do the trick – Wimpel Feb 18 '20 at 20:20
  • readr ::parse_number(data$Stimulus) – AndS. Feb 18 '20 at 20:24

4 Answers4

0

We can use sub to remove the substring "Narrow", followed by a , and zero or more spaces (\\s+), replace with blank ("") and convert to numeric

df1$New <- as.numeric(sub("Narrow,\\s*", "", df1$Stimulus))
akrun
  • 874,273
  • 37
  • 540
  • 662
0

You could use separate to separate the stimulus column into two vectors.

library(tidyr)
df %>%
  separate(col = stimulus, 
           sep = ", ",
           into = c("Text","Number"))
0

Maybe you can try the code below, using regmatches

df$new <- with(df, as.numeric(unlist(regmatches(stimulus,gregexpr("\\d+",stimulus)))))
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
-1

You want separate from the tidyr package.

library(dplyr)
df <- data.frame(x = c(NA, "a.b", "a.d", "b.c"))
df %>% separate(x, c("A", "B"))
#>      A    B
#> 1 <NA> <NA>
#> 2    a    b
#> 3    a    d
#> 4    b    c
tkerwin
  • 9,559
  • 1
  • 31
  • 47