R Apply () function for specific data columns

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

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

This will apply A to all y columns

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

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

 wifi[,1:3]+B 

also does not do what i expected / wanted.

+47
r dataframe apply
Aug 29 '13 at 5:48 on
source share
2 answers

Using the sample function data.frame and example (total +1 for all values)

 A <- function(x) x + 1 wifi <- data.frame(replicate(9,1:4)) wifi # X1 X2 X3 X4 X5 X6 X7 X8 X9 #1 1 1 1 1 1 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 data.frame(wifi[1:3], apply(wifi[4:9],2, A) ) #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 

Or even:

 data.frame(wifi[1:3], lapply(wifi[4:9], A) ) #or cbind(wifi[1:3], lapply(wifi[4:9], 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 
+37
Aug 29 '13 at 5:56 on
source share

lapply is probably a better choice than apply here, as they apply the first collages of your data.frame file to the array, which means that all columns must be of the same type. Depending on your context, this may have unintended consequences.

Sample:

 df[cols] <- lapply(df[cols], FUN) 

The vector "cols" may be variable names or indexes. I prefer to use names whenever possible (it is resistant to reordering columns). Therefore, in your case, it could be:

 wifi[4:9] <- lapply(wifi[4:9], A) 

An example of using column names:

 wifi <- data.frame(A=1:4, B=runif(4), C=5:9) wifi[c("B", "C")] <- lapply(wifi[c("B", "C")], function(x) -1 * x) 
+45
Aug 29 '13 at 6:36 on
source share



All Articles