2

I need to convert all rows of a dataframe to strings.

Here's a sample data:

1.12331,4.331123,4.12335435,1,"asd"
1.123453345,5.654456,4.889999,1.45456,"qwe"
2.00098,5.5445,4.768799,1.999999,"ttre"

I read this data into R, got a dataframe.

td<-read.table("test.csv", sep=',')

When I run apply(td, 2, as.character) on this data, I got

    V1       V2       V3       V4       V5    
[1,] "1.1233" "4.3311" "4.1234" "1.0000" "asd" 
[2,] "1.1235" "5.6545" "4.8900" "1.4546" "qwe" 
[3,] "2.0010" "5.5445" "4.7688" "2.0000" "ttre"

But when I do the same only on numeric columns, I got the different result:

apply(td[,1:4], 2, as.character)

     V1            V2         V3           V4        
[1,] "1.12331"     "4.331123" "4.12335435" "1"       
[2,] "1.123453345" "5.654456" "4.889999"   "1.45456" 
[3,] "2.00098"     "5.5445"   "4.768799"   "1.999999"

As a result I need a dataframe with values exactly the same as in source file. What I'm doing wrong?

1
  • As the other answers suggest, reading in your data in the correct format to begin with is the recommended way to deal with this, but for what it's worth, data.frame(lapply(td, as.character), stringsAsFactors=FALSE) should also work. Commented Feb 12, 2013 at 11:40

2 Answers 2

4

You can set colClasses in read.table() to make all columns as character.

 td <- read.table("test.csv", sep=',',colClasses="character")
 td
           V1       V2         V3       V4   V5
1     1.12331 4.331123 4.12335435        1  asd
2 1.123453345 5.654456   4.889999  1.45456  qwe
3     2.00098   5.5445   4.768799 1.999999 ttre

 str(td)
'data.frame':   3 obs. of  5 variables:
 $ V1: chr  "1.12331" "1.123453345" "2.00098"
 $ V2: chr  "4.331123" "5.654456" "5.5445"
 $ V3: chr  "4.12335435" "4.889999" "4.768799"
 $ V4: chr  "1" "1.45456" "1.999999"
 $ V5: chr  "asd" "qwe" "ttre"
Sign up to request clarification or add additional context in comments.

Comments

2

The best way to do this is the read the data in as character in the first place. You can do this with the colClasses argument to read.table:

td <- read.table("test.csv", sep=',', colClasses="character")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.