Reading csv file with numbers and rows in one column

I am importing a three-column CSV file. The end column is a series of records that are either integers or a quoted string.

The following are some examples:

1,4,"m"
1,5,20
1,6,"Canada"
1,7,4
1,8,5

When I import this with read.csv, they are all just included in the factors.

How can I tweak it so that it reads as integers and strings?

Thank!

+5
source share
3 answers

It is impossible, since this vector can have only one mode (for example character, numericor logical).

However, you can split the vector into two separate vectors: one with numerical values, the second with symbolic values:

vec <- c("m", 20, "Canada", 4, 5)

vnum <- as.numeric(vec)
vchar <- ifelse(is.na(vnum), vec, NA)

vnum
[1] NA 20 NA  4  5

vchar
[1] "m"      NA       "Canada" NA       NA      
+9
source

OP , @Andrie . .

, , . data.frame . @Andrie - , . , data.frame.

- ( , options(stringsAsFactors = FALSE)):

dat <- read.table(textConnection("1,4,'m'
1,5,20
1,6,'Canada'
1,7,4
1,8,5"),header = FALSE,sep = ",")

tmp <- as.list(as.numeric(dat$V3))
tmp[c(1,3)] <- dat$V3[c(1,3)]
dat$V3 <- tmp

str(dat)
'data.frame':   5 obs. of  3 variables:
 $ V1: int  1 1 1 1 1
 $ V2: int  4 5 6 7 8
 $ V3:List of 5
  ..$ : chr "m"
  ..$ : num 20
  ..$ : chr "Canada"
  ..$ : num 4
  ..$ : num 5

, . -, , data.frame, . , .

+6

. Dataframe ( ). , , . . (acolumn ), , , .

+2

All Articles