【问题标题】:Transforming vector into matrix-like object将向量转换为类似矩阵的对象
【发布时间】:2016-10-05 03:24:24
【问题描述】:

我在将向量转换为类似矩阵的对象时遇到了麻烦。乍一看,这一定是个很简单的问题,但我还没有解决。

问题描述:

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

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 

【问题讨论】:

    标签: r vector reshape


    【解决方案1】:

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

    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"
    

    【讨论】:

    • 非常好的自动检测NA应该包含在哪里!
    • @ProcrastinatusMaximus 谢谢!
    • 太棒了!完美的解决方案!喜欢它!
    • 只是为了添加嵌套ifelses 的替代品,可以使用max.col(sapply(c("€", "m²", "rooms"), grepl, m), "first") 之类的东西。
    猜你喜欢
    • 1970-01-01
    • 2017-06-10
    • 1970-01-01
    • 1970-01-01
    • 2021-04-29
    • 2010-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多