1

I’m parsing some JSON data in R and got this structure:

entry <- list("Ontario"="ON", "ON"="13.6")

When I try:

j <- entry["Ontario"]
population <- as.numeric(entry[j])

I get an error:

Error in if (population > 0) { : argument is of length zero

I think I’m not accessing the element correctly. What is the right way to get "13.6" as a number?

2

1 Answer 1

0

[] returns a subset of your list, so a list object. You want [[]], which returns a single element/value:


entry <- list("Ontario"="ON", "ON"="13.6")

# Returns subset of your list (a list object)
entry["Ontario"]
# $Ontario
# [1] "ON"

class(entry["Ontario"])
# [1] "list"

# Returns single element/value
j <- entry[["Ontario"]]

class(j)
# [1] "character"

as.numeric(entry[j])
# [1] 13.6
Sign up to request clarification or add additional context in comments.

1 Comment

Mention might be made of the effect of assignment j <- coupled wiith [[ forces a walk to the end of the chain that is some value, here '13.6'. Concerning quoting: A little less mysterious under lengths(entry) Ontario ON 1 1 so entry$ON [1] "13.6". entry2 <- list(Ontario = 'ON', ON = '13.6') also works because as read from left to right by compiler, ON (without quotes in second position) is an object, created in first position 'ON', so entry2$ON [1] "13.6", while entry3 <- list(Ontario = ON, ON = '13.6')` Error: object 'ON' not found, because not created yet.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.