Sweepy Dodo
Sweepy Dodo

Reputation: 1863

Looping over vectors (NOT looping over elements in a vector)

I currently have, say, 2 vectors

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

I am looking to do something like

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

I am obviously referring to x and y incorrectly. However, I am unsure as to how else to do so.

Upvotes: 0

Views: 102

Answers (2)

moonpainter
moonpainter

Reputation: 76

If I understand you correctly and you want to loop over entire vectors instead of vector elements, you can put your vectors into a list and then loop over the list.

Like so:

x <- c(1:10)
y <- c(11:20)

for (item in list(x, y)) {
    # your code
}

Edit (after your clarification):

If you want to turn both vectors into data.frames this is equally simple. First, put both vectors into a list, then modify them in your loop:

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]])
}

However a more R-ish solution would be to use the 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)

Upvotes: 4

Ronak Shah
Ronak Shah

Reputation: 388797

You could use Map and pass x and y as list argument and characters "x" and "y" as another argument. This will give you list of two separate dataframes

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

Or Maybe only with 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")))

Upvotes: 2

Related Questions