0

I've imported a data frame from a csv-file

dat3 <- read.csv(file.choose(),as.is = TRUE)

contains names and values. My problem is, that when I try to replace a value in the data frame, e.g.

dat3[3,6]<-12

then it just assumes, that "12" is a text string and not a value, thus preventing me from using that number to mathematical operations. I'd like to being able to replace some numbers in the data frame and using them for mathematical operations.

When I try adding 1 to dat3[3,6] I get: "Error in dat3[3, 6] + 1 : non-numeric argument to binary operator".

I've tried:

lapply(dat3[3,6], as.numeric)
dat3[3,6]<-as.numeric(12)

But it doesn't work. I have though no problems in using the already imported numbers in the data frame. This only happens for numbers which I replace.

pnuts
  • 58,317
  • 11
  • 87
  • 139
  • what is the original class of dat3, i guess it is already character, matrix is atomic data structure in R – sinalpha Nov 23 '15 at 15:27
  • This is why we store data in a `data.frame` (or better yet, IMHO, in a `data.table`) which allows for multiple data types (one per column). A matrix can only have one type, so if _any_ column is a character, the whole set will be converted. At base is the `list` type, which allows storage of multiple types (a `data.frame` is just a special type of `list`). Compare `cbind(matrix(1:2, nrow = 2), matrix(c("a","b"), nrow = 2))` and `list(first = 1:2, second = c("a","b"))` – MichaelChirico Nov 23 '15 at 15:27
  • So how would you import it as a dataframe in stead? – Danny Vain-Nielsen Nov 23 '15 at 15:36
  • you could use 'fread(pathtoyourfile)` – Heroka Nov 23 '15 at 15:41
  • But I think it's already a dataframe actually because I used read.csv. dat3 is also categorized under "data". – Danny Vain-Nielsen Nov 23 '15 at 15:51
  • `read.csv()` does create a data frame. `fread()` creates a data **table** unless you specify data frame. – Rich Scriven Nov 23 '15 at 16:46

1 Answers1

0

Yes!

I've found the answer!

It is:

dat[, c(3:6)] <- sapply(dat[, c(3:6)], as.numeric)

to convert column to numbers.

Thank you all!

  • 1
    It's better to specify what class a column should have then reading the csv file. You could look it up here http://stackoverflow.com/questions/2805357/specifying-colclasses-in-the-read-csv – nist Nov 23 '15 at 16:06