Nick Vence
Nick Vence

Reputation: 771

Extracting a value from a data.frame in R

I have a data frame, and I want to extract a single value.

hospital <- c("Clanton", "Shelby", "UAB")
score    <- c(1, 2, 3)
d        <- data.frame(hospital, score)
d[1,1]

Which returns

 Factor w/ 3 levels "Clanton","Shelby",..: 1

How do I return "Clanton" from this data frame?

Upvotes: 0

Views: 9232

Answers (2)

smorgasbordjorg
smorgasbordjorg

Reputation: 26

R should still be returning "Clanton", but it will be returning it as a factor, so it will list all factors within the column from which it was extracted. There are two ways you can address this. The first is defining your data frame columns as vectors of character values only.

d <- data.frame(hospital, score, stringsAsFactors=F)

The second way allows the data frame to keep the data as factors, but converts the factor to a character value when you extract it.

as.character(d[1,1])

Upvotes: 1

MichaelVE
MichaelVE

Reputation: 1344

When you want to return all the rows from the Clanton hospital it is possible with the following code:

d[d$hospital=="Clanton",]

Which selects all columns where the column hospital equals Clanton.

Upvotes: 1

Related Questions