从连接值创建新的矩阵列

时间:2013-07-14 23:57:08

标签: r

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

我用过

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

Concatenating N columns of text in R 创建连接值列表,但在将这些值放入矩阵中的新列时遇到问题 - 此代码的第二行语法错误。

我目前的代码:

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

3 个答案:

答案 0 :(得分:4)

  1. 您需要阅读R的基本介绍(请参阅tag wiki for links)。
  2. 目前,您已将0的向量创建为newcolumn。你的第二行代码是垃圾(正如你所正确的那样) - 见第1点。

    您可以将apply(format(matrix), 1, paste, collapse="")的结果与matrix联系起来。无需预先分配newcolumn

    请注意,matrix只能包含单一类型的数据(即数字或字符等),因此如果您包含character列,则整个矩阵将被强制转换为字符。< / p>

    # 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=""))
    

    另请注意,通常不要将对象命名为base R函数的名称(例如matrix

答案 1 :(得分:3)

cbind(matrix, paste0(as.character(matrix[,1]), as.character(matrix[,2])))应该做到这一点。矩阵必须转换为字符格式以适应'01'的情况。

答案 2 :(得分: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()

希望对您有帮助...

相关问题