r - 循环向量(不循环向量中的元素)

  • 本文关键字:向量 循环 元素 r loops vector
  • 更新时间 :
  • 英文 :


我目前有 2 个向量

x <- 1:2
y <- 3:4

我想做类似的事情

for (i in c("x","y"))
{
i <- data.frame(i)
i$flag <- ifelse(i == "x", 1, 0)  # just a flagging field
}

我显然错误地引用了x和y。但是,我不确定还能怎么做。

如果我理解正确,并且您想遍历整个向量而不是向量元素,您可以将向量放入列表中,然后在列表中循环。

这样:

x <- c(1:10)
y <- c(11:20)
for (item in list(x, y)) {
# your code
}

编辑(在您澄清后):

如果你想把两个向量都变成data.frames,这同样简单。首先,将两个向量放入一个列表中,然后在循环中修改它们:

x <- c(1:10)
y <- c(11:20)
list_of_vectors <- list(x, y)
for (i in seq_along(list_of_vectors)) {
list_of_vectors[[i]] <- as.data.frame(list_of_vectors[[i]])
}

然而,一个更R-ish的解决方案是使用lapply

x <- c(1:10)
y <- c(11:20)
list_of_vectors <- list(x, y)
list_of_vectors <- lapply(list_of_vectors, as.data.frame)

您可以使用Map并将xy作为list参数传递,字符"x""y"作为另一个参数传递。这将为您提供两个独立数据帧的列表

Map(function(x, y) data.frame(x, y = as.integer(y == "x")), list(x, y), c("x", "y"))
#[[1]]
#  x y
#1 1 1
#2 2 1
#[[2]]
#  x y
#1 3 0
#2 4 0

或者也许只有lapply

lst <- list(x = x, y = y)
lapply(seq_along(lst), function(x) 
data.frame(x = lst[[x]], y = as.integer(names(lst)[x] == "x")))

最新更新