[R] converting each column of a data frame into a matrix with n rows

David L Carlson dcarlson at tamu.edu
Wed May 17 21:35:48 CEST 2017


Not really enough info here since you don't specify much about the data frame or how the results should be provided, but maybe something like this:

y <- data.frame(matrix(1:100, 10, 10))
y.mat <- lapply(y, matrix, nrow=2)
str(y.mat)
List of 10
 $ X1 : int [1:2, 1:5] 1 2 3 4 5 6 7 8 9 10
 $ X2 : int [1:2, 1:5] 11 12 13 14 15 16 17 18 19 20
 $ X3 : int [1:2, 1:5] 21 22 23 24 25 26 27 28 29 30
 $ X4 : int [1:2, 1:5] 31 32 33 34 35 36 37 38 39 40
 $ X5 : int [1:2, 1:5] 41 42 43 44 45 46 47 48 49 50
 $ X6 : int [1:2, 1:5] 51 52 53 54 55 56 57 58 59 60
 $ X7 : int [1:2, 1:5] 61 62 63 64 65 66 67 68 69 70
 $ X8 : int [1:2, 1:5] 71 72 73 74 75 76 77 78 79 80
 $ X9 : int [1:2, 1:5] 81 82 83 84 85 86 87 88 89 90
 $ X10: int [1:2, 1:5] 91 92 93 94 95 96 97 98 99 100


-------------------------------------
David L Carlson
Department of Anthropology
Texas A&M University
College Station, TX 77840-4352


-----Original Message-----
From: R-help [mailto:r-help-bounces at r-project.org] On Behalf Of Davide Piffer
Sent: Wednesday, May 17, 2017 2:18 PM
To: r-help at r-project.org
Subject: [R] converting each column of a data frame into a matrix with n rows

I need to convert each vector of a dataframe into a matrix with 2 rows
and 2 columns (i.e. contingency table).
Note I don't want to convert the entire df into a matrix! I want to
apply a function that converts each 4 elements vector of a df into a 2
x 2 matrix.

I wrote something like this, but it will not work:

f_matrix=function(x){ matrix (x)
  nrow=2}
matrix_y=apply(y,2,function(x) f_matrix (x))

______________________________________________
R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list