Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a data read in by fread function to data.frame

Assume that I have a sample csv file which has 3 rows and 4 columns. Say it looks like the following:

name1 name2  name3 name4
11    12     13    14
21    22     23    24
31    32     33    34

I read it in using fread() (I am using the small sample for illustration purpose):

data <- fread(sample.csv, stringsAsFactors=FALSE)

then I do

class(data)

it will return

[1] "data.table" "data.frame"

I want to see the first element of the fourth column, I tried

data[1,4]

But it returns 4 (which I guess is the index of the column).

Interestingly, when I call the following

data[1,] 

or

data[1]

it returns the first row.

So I did

data <- data.frame(data)

to convert data to a data frame.

My questions:
1. Since the initial data has two classes, is there a way for me to choose one class and 'drop' the other? In my case, I just want to use the data as data frame.
2. In general, if data has more than one class, may we choose one class to keep? For instance, as.POSIXct() will return an object with two classes ("POSIXct" "POSIXt"). What if we just want to keep one of the classes? Any function works for this purpose in a generic way?

like image 349
StayLearning Avatar asked Oct 30 '22 17:10

StayLearning


1 Answers

if you want to use fread and want to get data as data frame just set the property of data.table to FALSE. By default it is true.

A data.table by default. A data.frame when argument data.table=FALSE;

E.g.

options(datatable.fread.datatable=FALSE).

See the documentation of R fread for reference. https://www.rdocumentation.org/packages/data.table/versions/1.10.4-2/topics/fread

like image 154
Haseeb Ashraf Avatar answered Nov 08 '22 09:11

Haseeb Ashraf