简体   繁体   中英

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?

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])

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM