And - 6 months ago 56

R Question

I have a trouble with transforming vector into matrix-like object. From the first sight, it must be very easy problem, but I didn't manage to solve it yet.

**Descriptinon of the problem:**

I have some long vector, which resembles the below mentioned one:

`m <- c("100€", "25m²", "2 rooms", "12m²", "4 rooms", "500€", "3 rooms")`

I wish to transfer it into the data.frame (or matrix) of the following structure:

`price surface rooms`

100€ 25m² 2 rooms

NA 12m² 4 rooms

500€ NA 3 rooms

Answer

You may try something like this, calculate the column and row index respectively and then assign the vector to the matrix using the indices:

```
col <- ifelse(grepl("€", m), 1, ifelse(grepl("m²", m), 2, 3))
col
# [1] 1 2 3 2 3 1 3
row <- cumsum(c(T, diff(col) < 0)) # calculate the row index based on the column index,
# when you encounter a decrease of the column index,
# increase the row index by one
row
# [1] 1 1 1 2 2 3 3
mat <- matrix(nrow = max(row), ncol = max(col))
mat[cbind(row, col)] <- m
mat
# [,1] [,2] [,3]
#[1,] "100€" "25m²" "2 rooms"
#[2,] NA "12m²" "4 rooms"
#[3,] "500€" NA "3 rooms"
```