Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am hoping to read a file and process it in R. It follows this format:

tibble(row=8,name="Shawn",state="Arizona", age=45,
comments="father=Alex;NSM;GNO;One:0.9995,0.13|Two:0.9991,0.55|Three:0.9996,0.33|Four:0.9986,0.22|Five:0.9987,0.22")
# A tibble: 1 x 5
        row name  state     age comment                                                                          
      <dbl> <chr> <chr>   <dbl> <chr>                                                                             
    1     8 Shawn Arizona    45 father=Alex;NSM;GNO;One:0.9995,0.13|Two:0.9991,0.55|Three:0.9996,0.33|Four:0.9986…

I would like to replace the last column with

comment
One:0.9995|Two:0.9991|Three:0.9996|Four:0.9986|Five:0.9987

and then subtract the floating number from 1:

comment
One:0.0005|Two:0.0009|Three:0.0004|Four:0.0014|Five:0.0013
See Question&Answers more detail:os

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

1 Answer

This function is not particularly performant or elegant, but it will give you exactly the output you asked for. It is not vectorized, but you could use sapply to fix that.

sample <- "father=Alex;NSM;GNO;One:0.9995,0.13|Two:0.9991,0.55|Three:0.9996,0.33|Four:0.9986,0.22|Five:0.9987,0.22"

extract_numbers <- function(x) {
  x <- sub(".*;", "", x)
  x <- gsub(",([0-9.]*)|", "", x)
  x <- strsplit(x, "|", fixed = TRUE)[[1]]
  do.call(
    "paste", 
    c(
      lapply(
        strsplit(x, ":"), 
        function(y) paste(y[1], sprintf("%6.4f", 1 - as.numeric(y[2])), sep = ":")
      ),
      sep = "|"
    )
  )
}

extract_numbers(sample)
# [1] "One:0.0005|Two:0.0009|Three:0.0004|Four:0.0014|Five:0.0013"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...