1

I have below data frame with two input string (input1 & input2 column) and need help to convert the output string (as described in the output column). I am looking for solution using base R (preferably regular expression)

df <- data.frame(input1=c("0000.00", "0000.00", "0000.00"),
                 input2 = c("23.3", "23", "2323.23"), 
                 output = c("0023.30", "0023.00", "2323.23"))
2
  • Hi,Please try something like this.hope this will help.df$output <- paste0(df$input1,"",df$input2) you have split the data after this to get your answer. Commented Jan 27, 2020 at 5:31
  • If you want to format numbers, then you can use functions like format or formatC. There may be a better way if you try and approach it like that Commented Jan 27, 2020 at 6:12

1 Answer 1

3

Try the following, it uses formatC to get the right output width and decimal places. It determines the numbers of digits before and after the decimal point with strsplit/sapply/nchar.

fun <- function(X){
  sp <- strsplit(as.character(X[[1]]), "\\.")
  m <- max(nchar(sapply(sp, '[[', 1)))
  n <- max(nchar(sapply(sp, '[[', 2)))

  formatC(as.numeric(as.character(X[[2]])),
          digits = n, width = m + n + 1, 
          format = "f", flag = "0")
}

fun(df)
#[1] "0023.30" "0023.00" "2323.23"
Sign up to request clarification or add additional context in comments.

Comments

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.