Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/visual-studio-2012/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 将向量转化为矩阵状对象_R_Vector_Reshape - Fatal编程技术网

R 将向量转化为矩阵状对象

R 将向量转化为矩阵状对象,r,vector,reshape,R,Vector,Reshape,我很难将向量转换成矩阵状的对象。乍一看,这一定是一个很容易的问题,但我还没有设法解决它 问题描述: 我有一些长向量,类似于下面提到的向量: m <- c("100€", "25m²", "2 rooms", "12m²", "4 rooms", "500€", "3 rooms") 您可以尝试以下方法,分别计算列和行索引,然后使用索引将向量分配给矩阵: col <- ifelse(grepl("€", m), 1, ifelse(grepl("m²", m), 2, 3)) co

我很难将向量转换成矩阵状的对象。乍一看,这一定是一个很容易的问题,但我还没有设法解决它

问题描述:

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

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

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

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"

col非常好的自动检测
NA
的位置@拖拉,谢谢!伟大的完美的解决方案!爱死它了!为了给嵌套的
ifelse
s添加一个替代方案,可以使用
max.col(sappy(c(“€)”,“m²”,“rooms”),“grepl,m),“first”)
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"