[英]Creating a new matrix column from concatenated values
I have a matrix with columns containing 0s and 1s, and I want to concatenate the values in each row to create a new column in that matrix with that concatenated string.我有一个包含 0 和 1 列的矩阵,我想连接每一行中的值,以在该矩阵中使用该连接字符串创建一个新列。
I used我用了
apply(format(matrix), 1, paste, collapse="")
from Concatenating N columns of text in R to create a list of concatenated values, but am having trouble getting those values into a new column in the matrix - the second line of this code has the wrong syntax.从连接 R 中的 N 列文本以创建连接值列表,但无法将这些值放入矩阵中的新列中 - 此代码的第二行语法错误。
my current code:我目前的代码:
newcolumn <- rep(0,times=nrow(matrix))
newcolumn[matrix[apply(format(matrix), 1, paste, collapse="")]]
matrix <- cbind(matrix, newcolumn)
At the moment, you have created a vector of 0
's as newcolumn
.目前,您已经创建了一个0
的向量作为newcolumn
。 Your second line of code is garbage (as you rightly noted) -- see point 1.您的第二行代码是垃圾(正如您正确指出的那样)-请参阅第 1 点。
You can cbind the results of apply(format(matrix), 1, paste, collapse="")
to matrix
.您可以将apply(format(matrix), 1, paste, collapse="")
的结果绑定到matrix
。 There is no need for preallocating newcolumn
.不需要预先分配newcolumn
。
Note that a matrix
can only hold a single type of data (ie numeric or character etc), as such if you include a character
column then the whole matrix will be coerced to character.请注意, matrix
只能保存单一类型的数据(即数字或字符等),因此如果包含character
列,则整个矩阵将被强制转换为字符。
# examples
# a character matrix containing the result + matrix coerced to character
charResults <- cbind(matrix, apply(format(matrix), 1, paste, collapse="") )
# you could use a data.frame to have different data classes in the same structure
dfResults <- cbind(as.data.frame(matrix), result = apply(format(matrix), 1, paste, collapse=""))
Also note, it is usually good practice not to name your objects the names of base
R functions (such as matrix
)另请注意,通常最好不要将对象命名为base
R 函数的名称(例如matrix
)
cbind(matrix, paste0(as.character(matrix[,1]), as.character(matrix[,2])))
should do the trick. cbind(matrix, paste0(as.character(matrix[,1]), as.character(matrix[,2])))
应该可以解决问题。 The matrix must be converted to character format to accommodate '01' cases.矩阵必须转换为字符格式以适应“01”情况。
Suppose that you have a Matrix A like the following;假设您有一个如下所示的矩阵 A;
A = [[1,2,3,4,5,6],
[11,12,13,14,15,16],
[21,22,23,24,25,26],
[31,32,33,34,35,36],
[41,42,43,44,45,46]]
You want to concatenate 1, 2, 3 columns with the 6.last column for constructing a new matrix as the following;您想将 1、2、3 列与 6.last 列连接起来,以构建一个新矩阵,如下所示; NewA =
[[1, 2, 3, 6],
[11,12,13,16],
[21,22,23,26],
[31,32,33,36],
[41,42,43,46]]
I have found the simplest solution of achieving it as;我找到了实现它的最简单的解决方案;
import numpy as np
NewA=np.concatenate((np.transpose(A)[0:3],np.transpose(A)[5:6])).transpose()
I wish it is helpful to you...希望对你有帮助...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.