ella
ella

Reputation: 11

Unexpected equal symbol error

I am trying to create a list where the column name is a date string coming from a list of strings. Let's say my list of strings is:

stringList=list("1-1-2001","1-1-2002")

I would like to create a list like this :

AList= list(stringList[[1]]=5)

So that I get something like this when I display it:

$`1-1-2001`
# [1] 5

Is this possible? This works if I write the string directly, otherwise I get error:

Error: unexpected '=' in "AList= list(stringList[[1]]="

Upvotes: 1

Views: 1219

Answers (2)

zx8754
zx8754

Reputation: 56189

Try this example, we need to use quotes or backticks to access invalid column names.

stringNames=c("1-1-2001","1-1-2002")

stringList <- list(5,6)
names(stringList) <- stringNames

#this gives errors
stringList$1-1-2001
# Error: unexpected numeric constant in "stringList$1"

#we can use backticks - ` `
stringList$`1-1-2001`
# [1] 5

#or we can use quotes - " " , thanks @Roland
stringList$"1-1-2001"
# [1] 5

Upvotes: 0

Roland
Roland

Reputation: 132706

Names that are not valid syntax should be avoided.

If you really want this (why?), setNames might be easiest:

Alist <- setNames(list(1, 2), stringList)

You could also do this:

Blist <- list()
Blist[[stringList[[1]]]] <- 3

Upvotes: 1

Related Questions