作为python用户,R到目前为止有点直观。但是,从旧列表创建新列表时遇到了问题。
特别是我有一个列表:
> x
[[1]]
[1] "Heads" "Tails" "Tails" "Heads" "Tails" "Heads"
[7] "Tails" "Tails" "Tails" "Heads" "Heads" "Tails"
... .... ... etc.
这是长度100。我想遍历此列表并创建一个值y为'Heads'= 1,'Tails'= -1的列表y。到目前为止我的尝试:
> for (val in x) {
ifelse(val == 'Heads', c(y,1), c(y,-1))}
其中附有一个空列表y。但是,结果是长度为2的列表。有人可以在这里帮助我吗?
您可以使用命名向量:
c("Heads" = 1, "Tails" = -1)[x[[1]]]
> Heads Tails Tails Heads Tails Heads Tails Tails Tails Heads Heads Tails
1 -1 -1 1 -1 1 -1 -1 -1 1 1 -1