[英]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]]=" 错误:“ AList = list(stringList [[1]] =“
Names that are not valid syntax should be avoided. 应避免使用无效语法的名称。
If you really want this (why?), setNames
might be easiest: 如果您真的想要这个(为什么?), setNames
可能是最简单的:
Alist <- setNames(list(1, 2), stringList)
You could also do this: 您也可以这样做:
Blist <- list()
Blist[[stringList[[1]]]] <- 3
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.