Home > Software engineering >  Taking out numeric data and multiply one and add another from a string
Taking out numeric data and multiply one and add another from a string

Time:12-12

I need to get the 2 or more numbers out of a string when there are letters behind them, then would need to multiply the first number by 8 and add the second to give 1 number in a new column. I have got as far as getting the 2 numbers out but, can't figure out how I would then do the sum for both numbers

Data looks like 2m6f 1m7f

x <- GBF$distance
x_numbers <- regmatches(x, gregexpr("[[:digit:]] ", x))  

Can get

2 6
1 7

Need to get

Distf

22
15

CodePudding user response:

1) Assuming the input x shown reproducibly in the Note at the end, replace non-digits with space and read using read.table giving a data frame whose columns are numeric. Then convert that to a matrix and matrix multiply it by the indicated vector giving the one column matrix shown. No packages are used.

as.matrix(read.table(text = gsub("\\D", " ", x))) %*% c(8, 1)
##      [,1]
## [1,]   22
## [2,]   15

1a) If the non-digits were always m and f then we can eliminate the gsub simplifying it to this:

as.matrix(read.table(text = x, sep = "m", comment = "f")) %*% c(8, 1)
##      [,1]
## [1,]   22
## [2,]   15

2) If the question had intended that the starting point be x_numbers then convert each element of it into a numeric vector giving a numeric matrix and cross product that with the indicated vector. Again, no packages are used.

crossprod(sapply(x_numbers, as.numeric), c(8, 1))
##      [,1]
## [1,]   22
## [2,]   15

Note

x <- c("2m6f", "1m7f")

CodePudding user response:

How about this?

Extract all numeric values into a list and then sapply a function across the list which does the numerical calculations needed:

library(stringr)
x = c("2m6f", "1m7f")
sapply(str_extract_all(x, "[:digit:]"), 
    function(x) (as.numeric(x[1]) * 8)   as.numeric(x[2])
    )
[1] 22 15
  •  Tags:  
  • r
  • Related