views:

90

answers:

5

Hi I have a matrix file that is 32X48 and I want to put all of the values into a single dimensional array in R. Right now I am only able to get the last row of data.

trgtFN_intensity <- "1074_B09_1- 4_5mM_Xgal_7d_W.cropped.resized.grey.png.red.median.colony.txt";

read.table(trgtFN_intensity, sep="\t") -> tmp_int

maxrow_int <- nrow(tmp_int);
maxcol_int <- ncol(tmp_int);

Elts_int <- -10;
for (row in 1:maxrow_int){rbind(Elts_int, tmp_int[row,]) -> Elts_int;}
av_int <- mean(Elts_int[Elts_int!=-10]);
sd_int <- sd(Elts_int[Elts_int!=-10]);

penalty_Matrix <- matrix(0, nrow=1536, ncol=1);
for (row in 1:maxrow_int)
{
    for (col in 1:maxcol_int)
{ 
    penalty_Matrix[col] <- tmp_int[row, col];

}
}

outFN <- paste(trgtFN_intensity, "array", sep=".");
write.table(penalty_Matrix, file = outFN, col.names=F, row.names=F, sep ="\t")

Any help would be greatly appreciated. Thank you

+3  A: 

From ?matrix: "A matrix is the special case of a two-dimensional 'array'." You can simply change the dimensions of the matrix/array.

Elts_int <- as.matrix(tmp_int)  # read.table returns a data.frame as Brandon noted
dim(Elts_int) <- (maxrow_int*maxcol_int,1)
Joshua Ulrich
Read table returns a data.frame not a matrix. Will this still work without as.matrix() ?
Brandon Bertelsen
@Brandon no it won't; good catch!
Joshua Ulrich
+1  A: 

You can use Joshua's solution but I think you need Elts_int <- as.matrix(tmp_int)

Or for loops:

z <- 1 ## Initialize
counter <- 1 ## Initialize
for(y in 1:48) { ## Assuming 48 columns otherwise, swap 48 and 32
for (x in 1:32) {  
z[counter] <- tmp_int[x,y]
counter <- 1 + counter
}
}

z is a 1d vector.

Brandon Bertelsen
+3  A: 

wtf? Either read it in with 'scan', or just do as.vector() on the matrix. You might want to transpose the matrix first if you want it by rows or columns. The solutions posted so far are so gross I'm not even going to try them...

> m=matrix(1:12,3,4)
> m
     [,1] [,2] [,3] [,4]
[1,]    1    4    7   10
[2,]    2    5    8   11
[3,]    3    6    9   12
> as.vector(m)
 [1]  1  2  3  4  5  6  7  8  9 10 11 12
> as.vector(t(m))
 [1]  1  4  7 10  2  5  8 11  3  6  9 12
Spacedman
KISS. I like it.
Brandon Bertelsen
+2  A: 

If we're talking about data.frame, then you should ask yourself are the variables of the same type? If that's the case, you can use rapply, or unlist, since data.frames are lists, deep down in their souls...

 data(mtcars)
 unlist(mtcars)
 rapply(mtcars, c) # completely stupid and pointless, and slower
aL3xa
+3  A: 

try c()

x = matrix(1:9, ncol = 3)

x
     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9

c(x)

[1] 1 2 3 4 5 6 7 8 9
Greg
That's a vector, and not a 1-d array.
hadley
hmm. That's true. Perhaps not a 1-d array, but a 1-d vector.
Greg