# Thread: Efficiently combining String and Number Arrays

1. ## Efficiently combining String and Number Arrays

I have two big matrices: A and B. A contains all numbers and B contains strings. For purpose of writing to a file I do cbind on A and B and use 'write' command to push it into a csv file. It works fine but in csv file I see that it writes A matrix first and then starts writing B after right hand bottom cell.

How can I do it in a cleaner way?

Thanks

3. ## The Following User Says Thank You to trinker For This Useful Post:

sak (03-05-2013)

4. ## Re: Efficiently combining String and Number Arrays

Can you post an abbreviated example of the code you have, the output you want, and the output you currently get?
Edit: not fast enough, trinker beat me to it

5. ## Re: Efficiently combining String and Number Arrays

A very simple example that I simulated is:

Code:
``````A = c('a','a','b','a','c')
B = c(1,3,4,5,6)
D = cbind(A,B)

> D
A   B
[1,] "a" "1"
[2,] "a" "3"
[3,] "b" "4"
[4,] "a" "5"
[5,] "c" "6"

write(D,"C:\\OutTest.csv")

When I open the csv, it looks as following:
a
a
b
a
c
1
3
4
5
6``````
Sorry I think I lied earlier. The 1,3,4,5,6 are not printed starting in right-bottom cell but in the same column i.e. B is printed after A.

6. ## Re: Efficiently combining String and Number Arrays

Try this method for writing to a file instead:

Code:
``write.table(D,"OutTest.csv", sep = ",", col.names = T, row.names=F, qmethod = "double")``

7. ## Re: Efficiently combining String and Number Arrays

Cool. It works.

Thanks

8. ## Re: Efficiently combining String and Number Arrays

Matrices in R only hold one data type. You want to use a data.frame data type. It's essentially a list of equal length vectors that displays like a matrix. The nice part about that is that the vectors can now be different data types. If you have separate numeric and character vectors A and B, then simply do

Code:
``````# You can have characters converted to factor data type if you prefer; defaults to TRUE
x <- data.frame(nums = A, strings = B, stringsAsFactors = FALSE)

# write.csv is just a wrapper for write.table with some select defaults, like sep = ","
write.csv(x, "Output.csv", row.names = FALSE)``````

9. ## The Following 2 Users Say Thank You to bryangoodrich For This Useful Post:

Dason (08-19-2012), sak (08-20-2012)

10. ## Re: Efficiently combining String and Number Arrays

Simple yet very insightful answer especially good for a novice users like.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts