2

我有一个包含 0 和 1 列的矩阵,我想连接每一行中的值以在该矩阵中使用该连接字符串创建一个新列。

我用了

apply(format(matrix), 1, paste, collapse="") 

连接 R 中的 N 列文本 创建连接值列表,但无法将这些值放入矩阵中的新列 - 此代码的第二行语法错误。

我当前的代码:

newcolumn <- rep(0,times=nrow(matrix))
newcolumn[matrix[apply(format(matrix), 1, paste, collapse="")]]
matrix <- cbind(matrix, newcolumn)
4

3 回答 3

4
  1. You need to read a basic introduction to R (see the tag wiki for links).

At the moment, you have created a vector of 0's as newcolumn. Your second line of code is garbage (as you rightly noted) -- see point 1.

You can cbind the results of apply(format(matrix), 1, paste, collapse="") to matrix. There is no need for preallocating newcolumn.

Note that a matrix can only hold a single type of data (i.e. numeric or character etc), as such if you include a character column then the whole matrix will be coerced to 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)

于 2013-07-15T00:11:47.090 回答
3

cbind(matrix, paste0(as.character(matrix[,1]), as.character(matrix[,2])))应该做的伎俩。矩阵必须转换为字符格式以适应“01”的情况。

于 2013-07-15T00:20:50.257 回答
0

假设您有一个如下所示的矩阵 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]]

您想将 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]]

我找到了实现它的最简单的解决方案;

import numpy as np
NewA=np.concatenate((np.transpose(A)[0:3],np.transpose(A)[5:6])).transpose()

我希望它对你有帮助...

于 2020-12-05T12:59:42.487 回答