我想创建以下列表
myList[[1]][1] 10
myList[[1]][2] 20
myList[[1]][3] 30 40
所以我编写了以下代码,但似乎我做错了:
myList <- vector(mode = "list")
myList[[length(myList)+1]] <- 10
# myList[[length(myList)+1]][1] <- 10 # it seems more reasonable, but it does not work either
myList[[length(myList)]][2] <- 20
myList[[length(myList)]][3] <- c(30, 40)
print(myList)
myList [[1]] [3]的第三个元素是否也应该是一个列表?
答案 0 :(得分:2)
您无法创建此列表:
myList[[1]][1] 10
myList[[1]][2] 20
myList[[1]][3] 30 40
这意味着myList[[1]]
将等于:
[1] 10
[2] 20
[3] 30 40
这不是R中可接受的变量,因为你暗示向量的元素3本身就是一个向量。
但是,这是:
[[1]]
[1] 10
[[2]]
[1] 20
[[3]]
[1] 30 40
所以你可以这样做:
myList = list()
myList = c(myList, 10)
myList = c(myList, 20)
myList = c(myList, list(c(30, 40)))
结果是
> myList
[[1]]
[1] 10
[[2]]
[1] 20
[[3]]
[1] 30 40