[R] Issue with assigning text to matrix

Sarah Goslee sarah.goslee at gmail.com
Tue Jun 1 15:47:06 CEST 2010


On Tue, Jun 1, 2010 at 5:04 AM, Jessica Queree
<j.j.queree at googlemail.com> wrote:
> My issue relates to adding text to a matrix and finding that the text is
> converted to a number.
>

A matrix can only hold one type of data. Since you started with character,
that's what you get.

A dataframe can hold different types of data, both character and numeric.
If you convert your matrix to a dataframe with dataf.frame() it can hold
your output in the manner you expect.

testOutput <- data.frame(matrix(nrow = 200, ncol = 5))

Sarah
>
> This is the section of code I'm having trouble with:
>
>
>
> # First, I load in a list of names from a .csv file to 'names'
>
> names <- read.csv(file("Names.csv"))
>
>
>
> # Then I define a matrix which will be populated with various test
> statistics, with several rows for each entry in names
>
>
>
> testOutput <-matrix(nrow = 200, ncol = 5)
>
> for (i in 1:nrow(names)){
>
>
>
>            testOutput[i,1] <- names[i,1]
>
>            testOutput[i,2] <- names[i,2]
>
>
>
>            # test statistics code here
>
>
>
> }
>
>
> That is, the names are now converted to numbers. I think this might have
> something to do with the way I've defined the testOutput matrix, but haven't
> been able to find any information about how to fix it. Can anyone help?
>
>
>
> Many thanks.
>



-- 
Sarah Goslee
http://www.functionaldiversity.org



More information about the R-help mailing list