Claudio Moneo
Claudio Moneo

Reputation: 569

read.table ignoring white spaces and converting to character

I am reading a csv-file into R using read.table. When I open the file in a text editor, it looks like this :

variable 1;variable 2;variable 3; ...
name1;0,00;1,00;0,00;...
name2;1,00;2,00;0,00;...
...

As you can see, the first variable consist of characters, while all of the other ones are numeric but with comma seperated decimals.

Note: Unfortunately, there are also some that are encoded as -- instead of 0,00

Now when I use read.table I specify

dec=","
sep=";"
header=TRUE
stringsAsFactors=FALSE

but this does not work. There are two issues:

How can I fix this?

Upvotes: 1

Views: 760

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388907

Use read.csv2 which has sep = ';' and dec = ',' as default value. To keep the spaces in column names include check.names = FALSE.

data <- read.csv2('filename.csv', check.names = FALSE)

For example if we copy the text from OP as text.

text = 'variable 1;variable 2;variable 3
name1;0,00;1,00;0,00
name2;1,00;2,00;0,00'

data <- read.csv2(text = text, check.names = FALSE)
data

#      variable 1 variable 2 variable 3
#name1          0          1          0
#name2          1          2          0

str(data)

#'data.frame':  2 obs. of  3 variables:
# $ variable 1: num  0 1
# $ variable 2: num  1 2
# $ variable 3: num  0 0

Upvotes: 1

Related Questions