Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (5.3k points)

I want to use the apply function on a data frame but only apply the function to the last 5 columns.

B<- by(wifi,(wifi$Room),FUN=function(y){apply(y, 2, A)})

This applies A to all the columns of y

B<- by(wifi,(wifi$Room),FUN=function(y){apply(y[4:9], 2, A)})

This applies A only to columns 4-9 of y, but the total return of B strips off the first 3 columns... I still want those, I just don't want A applied to them.

wifi[,1:3]+B 

also does not do what I expected/wanted.

1 Answer

0 votes
by

You can use the apply() function on specific data frame columns as follows:

A <- function(x) x + 1

wifi <- data.frame(replicate(9,1:4))

wifi

data.frame(wifi[1:3], apply(wifi[4:9],MARGIN = 2, A) )

  X1 X2 X3 X4 X5 X6 X7 X8 X9

1  1  1  1  2  2  2  2  2  2

2  2  2  2  3  3  3  3  3  3

3  3  3  3  4  4  4  4  4  4

4  4  4  4  5  5  5  5  5  5

OR

cbind(wifi[1:3], apply(wifi[4:9],2, A) )

  X1 X2 X3 X4 X5 X6 X7 X8 X9

1  1  1  1  2  2  2  2  2  2

2  2  2  2  3  3  3  3  3  3

3  3  3  3  4  4  4  4  4  4

4  4  4  4  5  5  5  5  5  5

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...