Loop over Variables in a Data Frame or Environment¶

Description¶

foreach evaluates an expression given as second argument by substituting in variables. The expression may also contain assignments, which take effect in the callers environment.

foreach(...)

Arguments¶

...

tagged and untagged arguments. The tagged arguments define the ‘variables’ that are looped over, the first untagged argument defines the expression wich is evaluated.

Examples¶

x <- 1:3
y <- -(1:3)
z <- c("Uri","Schwyz","Unterwalden")
print(x)
 1 2 3
print(y)
 -1 -2 -3
print(z)
 "Uri"         "Schwyz"      "Unterwalden"
foreach(var=c(x,y,z),          # assigns names
names(var) <- letters[1:3]   # to the elements of x, y, and z
)
print(x)
a b c
1 2 3
print(y)
a  b  c
-1 -2 -3
print(z)
a             b             c
"Uri"      "Schwyz" "Unterwalden"
ds <- data.set(
a = c(1,2,3,2,3,8,9),
b = c(2,8,3,2,1,8,9),
c = c(1,3,2,1,2,8,8)
)
print(ds)
a b c
1 1 2 1
2 2 8 3
3 3 3 2
4 2 2 1
5 3 1 2
6 8 8 8
7 9 9 8
ds <- within(ds,{
description(a) <- "First item in questionnaire"
description(b) <- "Second item in questionnaire"
description(c) <- "Third item in questionnaire"

wording(a) <- "What number do you like first?"
wording(b) <- "What number do you like second?"
wording(c) <- "What number do you like third?"

foreach(x=c(a,b,c),{ # Lazy data documentation:
labels(x) <- c(    # a,b,c get value labels in one statement
one = 1,
two = 2,
three = 3,
"don't know" = 8,
"refused to answer" = 9)
missing.values(x) <- c(8,9)
})
})
as.data.frame(ds)
a  b  c
1  1  2  1
2  2 NA  3
3  3  3  2
4  2  2  1
5  3  1  2
6 NA NA NA
7 NA NA NA
ds <- within(ds,foreach(x=c(a,b,c),{
measurement(x) <- "interval"
}))
as.data.frame(ds)
a  b  c
1  1  2  1
2  2 NA  3
3  3  3  2
4  2  2  1
5  3  1  2
6 NA NA NA
7 NA NA NA