Foreach: Loop over Variables in a Data Frame or Environment

Description Usage Arguments Examples

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.

Usage

1

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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
x <- 1:3
y <- -(1:3)
z <- c("Uri","Schwyz","Unterwalden")
print(x)
print(y)
print(z)
foreach(var=c(x,y,z),          # assigns names
  names(var) <- letters[1:3]   # to the elements of x, y, and z
  )
print(x)
print(y)
print(z)

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

ds <- within(ds,foreach(x=c(a,b,c),{
  measurement(x) <- "interval"
  }))

as.data.frame(ds)

Example output

Loading required package: lattice
Loading required package: MASS

Attaching package:memiscThe following objects are masked frompackage:stats:

    contr.sum, contr.treatment, contrasts

The following object is masked frompackage:base:

    as.array

[1] 1 2 3
[1] -1 -2 -3
[1] "Uri"         "Schwyz"      "Unterwalden"
a b c 
1 2 3 
 a  b  c 
-1 -2 -3 
            a             b             c 
        "Uri"      "Schwyz" "Unterwalden" 
  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
   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
   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

memisc documentation built on May 2, 2019, 5:45 p.m.

Related to Foreach in memisc...