1) Assuming that what is wanted is the mean of the two numbers in each component of X, remove the first and last character and read what is left using read.table creating a data frame in which each row is formed from one component of X. Finally use rowMeans on that.
No packages are used.
rowMeans(read.table(text = sub(".(.*).", "\\1", X), sep = ","))
## [1] -48.0 -61.7 -52.0 -43.5 -51.2 -43.1 -43.5 -47.2
This can also be written as a pipeline:
X |>
sub(".(.*).", "\\1", x = _) |>
read.table(text = _, sep = ",") |>
rowMeans()
## [1] -48.0 -61.7 -52.0 -43.5 -51.2 -43.1 -43.5 -47.2
1a) A variation of this is the following that returns the result of read.table with the means as an extra column.
transform(read.table(text = sub(".(.*).", "\\1", X), sep = ","),
mean = (V1 + V2) / 2)
## V1 V2 mean
## 1 -48.2 -47.8 -48.0
## 2 -61.9 -61.5 -61.7
## 3 -52.2 -51.8 -52.0
## 4 -43.7 -43.3 -43.5
## 5 -51.4 -51.0 -51.2
## 6 -43.3 -42.9 -43.1
## 7 -43.7 -43.3 -43.5
## 8 -47.4 -47.0 -47.2
or as a pipeline:
X |>
sub(".(.*).", "\\1", x = _) |>
read.table(text = _, sep = ",") |>
transform(mean = (V1 + V2) / 2)
2) A similar approach using strapply also works. This applies the indicated function, expressed using formula notation, to the capture groups.
library(gsubfn)
strapply(format(X), "^.(.*),(.*).$", ~ mean(as.numeric(c(x, y))), simplify = TRUE)
## [1] -48.0 -61.7 -52.0 -43.5 -51.2 -43.1 -43.5 -47.2