将矢量转换为类似矩阵的对象

时间:2016-10-04 18:57:57

标签: r vector reshape

我在将矢量转换为类似矩阵的对象时遇到了麻烦。从第一眼看,它一定是非常容易的问题,但我还没有设法解决它。

问题的描述:

我有一些长矢量,类似于下面提到的那个:

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

我希望将其转移到以下结构的data.frame(或矩阵)中:

  price surface    rooms
   100€    25m²  2 rooms 
     NA    12m²  4 rooms
   500€     NA   3 rooms 

1 个答案:

答案 0 :(得分:5)

您可以尝试这样的方法,分别计算列和行索引,然后使用索引将向量分配给矩阵:

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"