2

I have a data frame that looks like this

position=c("24,201", "8,915", "45,877:1","251,603")
evindence=c("RA", "RA","RA","RA")
test = data.frame(evindence,position)
  evindence position
1        RA   24,201
2        RA    8,915
3        RA 45,877:1
4        RA  251,603

I would like to use stringr or other tidyr applications to replace "," = "." and then create a new column when there is a string like ":".

I would like my dataset to look like this:

  evindence position insertion
1        RA   24201     NA
2        RA    8915     NA
3        RA   45877     1
4        RA  251603     NA

Any help or direction are appreciated

1
  • 2
    at least you were consistent with your typo :) Commented Jan 26, 2021 at 17:25

2 Answers 2

3

Something like this might do the trick :

 # should remove the "," from the position column
test$position = gsub(",", "", position)
# should check if string contains :
test$insertion = grepl(":", test$position, fixed=TRUE)
# should extract anything before ":"
test$position = sapply(strsplit(test$position, "\\:"), "[", 1)
Sign up to request clarification or add additional context in comments.

1 Comment

sorry for all the edits, had to redo it a few times. should do what you want now though :)
2

and here the tidyverse option. Not saying it's better. Just another option. You'll get an appropriate warning for the NAs - sometimes you want warnings.

library(tidyverse)
position=c("24,201", "8,915", "45,877:1","251,603")
evindence=c("RA", "RA","RA","RA")
test = data.frame(evindence,position)

test %>%
  mutate(position = str_replace(position, ",", "\\.")) %>%
  separate(position, c("position", "insertion"), sep = ":")
#> Warning: Expected 2 pieces. Missing pieces filled with `NA` in 3 rows [1, 2, 4].
#>   evindence position insertion
#> 1        RA   24.201      <NA>
#> 2        RA    8.915      <NA>
#> 3        RA   45.877         1
#> 4        RA  251.603      <NA>

Created on 2021-01-26 by the reprex package (v0.3.0)

1 Comment

note if your intention is to create doubles, you still need to call "as.numeric"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.