Luke Bridgman - 5 months ago 18

R Question

I have a dataset in which I wish to sum each value in column n, with its corresponding value in column (n+(ncol/2)); i.e., so I can sum a value in column 1 row 1 with a value in column 12 row 1, for a dataset with 22 columns, and repeat this until column 11 is summed with column 22. The solution needs to work for hundreds of rows.

How do I do this using R, while ignoring the column names?

Answer

Suppose your data is

```
d <- setNames(as.data.frame(matrix(rnorm(100 * 22), nc = 22)), LETTERS[1:22])
```

You can do a simple matrix addition using numbers to select the columns:

```
output <- d[, 1:11] + d[, 12:22]
```

so, e.g.

```
all.equal(output[,1], d[,1] + d[,12])
# [1] TRUE
```