how to add up values before and after a slash

63 views Asked by At

Hi I have a question related to slash.

the data I'm working on is like:

X Y Z
12/22 14/32 22/34

I would like to get the mean of the values before and after the slash.

X Y Z
17 18 28

How can I do this?

3

There are 3 answers

0
junkka On BEST ANSWER

To get the mean of each cell even if there are more than one row in the data.frame:

as.data.frame(
  apply(dat, 1:2, function(x) {
      mean(as.integer(unlist(strsplit(x,"/"))))
    }
  )
)
0
Cath On
values<-c("12/22","14/32","22/34")

> unlist(lapply(strsplit(values,"/"),function(values2){mean(as.numeric(values2))}))
[1] 17 23 28
0
Sven Hohenstein On

Another solution:

as.data.frame(lapply(dat, function(x) mean(c(as.integer(sub("/.+", "", x)), 
                                             as.integer(sub(".+/", "", x))))))

where dat is the name of your data frame.