简体   繁体   中英

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.

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.

my current code:

newcolumn <- rep(0,times=nrow(matrix))
newcolumn[matrix[apply(format(matrix), 1, paste, collapse="")]]
matrix <- cbind(matrix, newcolumn)
  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 (ie 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 )

cbind(matrix, paste0(as.character(matrix[,1]), as.character(matrix[,2]))) should do the trick. The matrix must be converted to character format to accommodate '01' cases.

Suppose that you have a Matrix A like the following;
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; 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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM