Assuming that the block of columns are based on
the first two characters, i.e. `A1`

,
`A2`

, we can split this into different
blocks by using `substr`

to extract the
first two characters from the column names and use
this as index to `split`

. Then, we can
either use `apply`

with
`range`

and `diff`

to get
the result or use `pmax`

and
`pmin`

.

```
indx <- substr(colnames(df), 1,2)
```

If the grouping is not based on the
`column names`

but on the position,
this should also work

```
indx <- (1:ncol(df)-1)%/%4 +1
res1 <- sapply(split(seq_len(ncol(df)),
indx),
function(i) do.call(pmax,df[,i,
drop=FALSE])-
do.call(pmin,
df[,i, drop=FALSE]))
```

Or

```
res2 <-
sapply(split(seq_len(ncol(df)), indx),
function(i) apply(df[,i, drop=FALSE],
1,
function(x)
diff(range(x))) )
identical(res1, res2)
#[1] TRUE
res1
# A1 A2
#[1,] 1.680105 2.443593
#[2,] 7.701992 2.447799
#[3,] 7.740707 1.367992
```

Or using your code

```
newmatrix <- matrix(0, nrow(df), 2)
#here the example dataset is only 7 columns
for(i in (1:nrow(df))) newmatrix[i,1] <-
diff(range(df[i,1:4]))
for(i in (1:nrow(df))) newmatrix[i,2] <-
diff(range(df[i,5:7]))
newmatrix
# [,1] [,2]
#[1,] 1.680105 2.443593
#[2,] 7.701992 2.447799
#[3,] 7.740707 1.367992
```

If you have many blocks of columns, you can try
a double `for`

loop

```
lst <- split(seq_len(ncol(df)),
indx) #keep the columns to group in a `list`
newmatrix <- matrix(0, nrow(df), 2) #he
for(i in 1:nrow(df)){
for(j in seq_along(lst)){
newmatrix[i,j] <- diff(range(df[i,
lst[[j]]]))
}
}
newmatrix
# [,1] [,2]
#[1,] 1.680105 2.443593
#[2,] 7.701992 2.447799
#[3,] 7.740707 1.367992
```

### data

```
df <- structure(list(A1B1 =
c(-0.37014356, 3.03017573, 3.50183121),
A1B2 = c(1.08841141, 1.39812421, 1.51249433), A1B3
= c(-0.126574243,
0.243516558, -0.775449944), A1B4 = c(-0.5916936,
-4.6718165,
-4.2388756), A2B1 = c(1.682673457, -0.378640756,
-0.456911873
), A2B2 = c(-0.427706432, 2.039940436,
0.431838943), A2B3 = c(-0.76091938,
-0.40785893, 0.91108052)), .Names = c("A1B1",
"A1B2", "A1B3",
"A1B4", "A2B1", "A2B2", "A2B3"), class =
"data.frame", row.names = c(NA,
-3L))
```