0

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?

1
  • 2
    It works for me. And with as.character(d[1,1]). Commented Mar 11, 2015 at 5:25

2 Answers 2

1

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])
Sign up to request clarification or add additional context in comments.

3 Comments

@smorgasbordjorg It is good practise to acknowledge the person if you got inspired/copy an answer from the comments
@Pascal this has become a common practice on SO lately, there's nothing you can about really, rather post your comments as answers.
I am curious why the question was answered in the comments. However I appreciate the explanation.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.