Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
156 views
in Technique[技术] by (71.8m points)

r - Replace one string and create a column with another

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

question from:https://stackoverflow.com/questions/65905117/replace-one-string-and-create-a-column-with-another

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...