2

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)
Community
  • 1
  • 1

3 Answers3

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)

Community
  • 1
  • 1
mnel
  • 113,303
  • 27
  • 265
  • 254
  • Thanks so much - I am very much in need of more of a basic intro to R, admittedly, but am unfortunately rather more rushed than I'd like in doing this project. Your charResults code was exactly what I needed - thank you so much. – user2581871 Jul 15 '13 at 12:59
3

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.

geotheory
  • 22,624
  • 29
  • 119
  • 196
0

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...

cinsdikici
  • 99
  • 1
  • 1
  • The asker's question is in relation to `r` but your solution provided is for the `python` language. – etch_45 Dec 05 '20 at 15:23