TTT
TTT

Reputation: 4434

Read a CSV file in R, and select each element

Sorry if the title is confusing. I can import a CSV file into R, but once I would like to select one element by providing the row and col index. I got more than one elements. All I want is to use this imported csv as a data.frame, which I can select any columns, rows and single cells. Can anyone give me some suggestions?

Here is the data:

SKU On  Off Duration(hr)    Sales
C010100100  2/13/2012   4/19/2012 17:00 1601    238
C010930200  5/3/2012    7/29/2012 0:00  2088    3
C011361100  2/13/2012   5/25/2012 22:29 2460    110
C012000204  8/13/2012   11/12/2012 11:00    2195    245
C012000205  8/13/2012   11/12/2012 0:00 2184    331

CODE:

Dat = read.table("Dat.csv",header=1,sep=',')
Dat[1,][1]  #This is close to what I need but is not exactly the same
         SKU
1 C010100100
Dat[1,1]    # Ideally, I want to have results only with C010100100
[1] C010100100
3861 Levels: B013591100 B024481100 B028710300 B038110800 B038140800 B038170900 B038260200 B038300700 B040580700 B040590200 B040600400 B040970200 ... YB11624Q1100

Thanks!

Upvotes: 1

Views: 2181

Answers (1)

Matthew Lundberg
Matthew Lundberg

Reputation: 42629

You can convert to character to get the value as a string, and no longer as a factor:

as.character(Dat[1,1])

You have just one element, but the factor contains all levels.

Alternatively, pass the option stringsAsFactors=FALSE to read.table when you read the file, to prevent creation of factors for character values:

Dat = read.table("Dat.csv",header=1,sep=',', stringsAsFactors=FALSE )

Upvotes: 2

Related Questions