3

Why does c(...) returns a number instead of the string in the example below?

> Location$NamePrint
[1] Burundi
273 Levels: Afghanistan Africa ...

> ParentLocation$NamePrint
[1] Eastern Africa
273 Levels: Afghanistan Africa ...

> c(Location$NamePrint, ParentLocation$NamePrint)
[1] 36 71

These numbers are the position of the strings in the levels?

My goal is to create a vector with these two elements (their string value), using c(Location$NamePrint, ParentLocation$NamePrint)

1
  • use as.character like this c(as.character(Location$NamePrint), as.character(ParentLocation$NamePrint)) Commented Apr 20, 2018 at 17:53

2 Answers 2

7

Because it's a factor. For example:

x <- as.factor("a")
c(x)

# [1] 1

To resolve this, we can treat x as.character:

x <- as.character("a")
c(x)

# [1] "a"

As @joran mentions, there's a handy function in forcats for this as well, forcats::fct_c().

See ?c and read the details section for additional information:

Note that factors are treated only via their internal integer codes; one proposal has been to use:

x <- as.factor("a")
y <- as.factor("b")

c.factor <- function(..., recursive=TRUE) unlist(list(...), recursive=recursive)

c.factor(x, y)

# [1] a b
# Levels: a b
Sign up to request clarification or add additional context in comments.

2 Comments

Options: round trip from character back to factor or use the handy forcats::fct_c() function.
Nice, I've included this option in the answer
2

The structure (str()) of your objects will reveal that they are factors.

demo1 <- as.factor("Burundi")
demo2 <- as.factor("Eastern Africa")
str(demo1)

See:

> str(demo1)
 Factor w/ 1 level "Burundi": 1

So when you concatenate them, this happens:

> c(demo1, demo2)
[1] 1 1

If you want to bring them in to a vector with their text, use as.character:

> c(as.character(demo1), as.character(demo2))
[1] "Burundi"        "Eastern Africa"

Or even better, do this to the original vectors, e.g.:

demo1 <- as.character(demo1)

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.