从旧列表创建新列表(R)

时间:2019-09-25 14:24:49

标签: r list for-loop if-statement append

作为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的列表。有人可以在这里帮助我吗?

2 个答案:

答案 0 :(得分:1)

您可以使用命名向量:

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 

或者使用布尔值转换为数字来获取向量(优雅但可能不是最有效的):

(x[[1]] == "Heads") * 2 - 1
> [1]  1 -1 -1  1 -1  1 -1 -1 -1  1  1 -1

答案 1 :(得分:0)

据我了解,您有一个带有两个唯一值的嵌套列表。您可以为此使用lapply

x <- list(list("Heads","Tails","Heads"),list("Heads","Tails","Tails"))
lapply(x, function(x){y <- ifelse(x == "Heads", 1, -1); names(y) <- x; y})

# [[1]]
# Heads Tails Heads 
# 1    -1     1 
# 
# [[2]]
# Heads Tails Tails 
# 1    -1    -1

或者,如果不需要名称,请使用rapply

x <- list(list("Heads","Tails","Heads"),list("Heads","Tails","Tails"))
rapply(x, function(x){ifelse(x == "Heads", 1, -1)})