yankee
yankee

Reputation: 1

Replace for loop with apply function

My question is how to use "apply" function to do what "for loop" does in this example:

mtcars

for (i in colnames(mtcars)){
    print(head(mtcars[i]))
}

What I need is to get R to read one column after the other, ideally by index (ie mtcars[1], then mtcars[2], then mtcars[3]...) rather than colnames.

Your help is highly appreciated.

Thanks

Upvotes: 0

Views: 1249

Answers (1)

Nader Hisham
Nader Hisham

Reputation: 5414

Use the apply function

apply(mtcars, 2 ,head)

this is the result

                   mpg cyl disp  hp drat    wt  qsec vs am gear carb
Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
Valiant           18.1   6  225 105 2.76 3.460 20.22  1  0    3    1

Explanation

2 in the parameter of apply function means you're going to pass each column to your defined function , if you pass 1 instead of 2 this means that you're going to send each row instead of column

Upvotes: 1

Related Questions