0
$\begingroup$

I would like to transform a string into a number. This is my code:

test <- starwars home <- test$homeworld home <- as.numeric(home) 

but I have this error:

Error: 'list' object cannot be coerced to type 'double' 

My goal is to assign a number to every homeworld. Obviously the lines with the same homeworld will have the same number assigned.

How can I fix my code?

$\endgroup$

1 Answer 1

1
$\begingroup$

The way I read it, you want to transform home to contain numbers instead of text, with similar numbers representing similar homeworlds.

As r correctly states, you cannot turn a list into a single numeric (double) value. Instead, you first have to convert the list into a factor.

To do this in R, you run:

data(starwars, package = "dplyr") df <- starwars home <- df$homeworld home_numeric <- as.numeric(as.factor(home)) 

Hope this helps!

$\endgroup$
3
  • $\begingroup$ With this example works, but with my real dataset I have a list of NA value and I don't understand why.. $\endgroup$ Commented Jan 4, 2022 at 13:29
  • $\begingroup$ Please provide a reproducible example of your real dataset, as otherwise it is impossible to provide a fitting answer to your question. $\endgroup$ Commented Jan 4, 2022 at 13:36
  • $\begingroup$ Ok, now it works! Thank you! $\endgroup$ Commented Jan 4, 2022 at 13:54

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.