Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 209860

divide columns using pattern in colnames

$
0
0

Assuming I have the following simplified table which has dynamic columns a_x (where x is an index e.g 0, 1, 2, 3, 4...) and b_x respectively. The number of a columns is always equal to the number of b columns but the total number of columns can be dynamic (not always 3 a and 3 b). To make it clearer the following example depicts the structure of my data:

> d <- read.table(text = "10 20 25 0.3 0.23 0.34 
                          40 20 30 0.25 0.4 0.45")
> names(d) <- c("a_0", "a_1", "a_2", "b_0", "b_1", "b_2")
> d
   a_0 a_1 a_2  b_0  b_1  b_2
1  10  20  25   0.30 0.23 0.34
2  40  20  30   0.25 0.40 0.45

I would like to divide a columns with the corresponding b columns and save the results in new c columns. In order to do the divisions I use the transform() function (with hard-coded colnames) like this:

transform(d, c_0 = as.numeric(as.character(a_0)) / as.numeric(as.character(b_0)))

How can I do this step automatically using (probably) a pattern in colnames given the fact the number of columns of my input data is not always the same.

Any help would be appreciated


Viewing all articles
Browse latest Browse all 209860

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>