简体   繁体   中英

doing operations on multiple columns of data frame at once

Assume I have a list of dataframe and I want to do some operations on columns 1,2 and 4 and some other operations on columns 3,5 and 6 all at the same time.

Lets say I want to multiply columns 1,2,4 by 2 and columns 3,5 and 6 by 3.

Using lapply I can do one of these operations at once but not both:

A<- apply(list, function(x) {2*X[,c(1,2,4)] 3*X[,c(3,5,6)]}) 

This gives error message like unrecognized numeric constant. How can I do them all at the same time. This is because if I do one of them I am returning columns like 1,2,4.

We can use cbind to combine both the subsets after multiplying by their constants.

lapply(list_df, function(df) cbind(df[c(1, 2, 4)] * 2, df[c(3, 5, 6)] * 3))

#[1]]
#  a  b  d  c  e  f
#1 2  8 20 21 15 18
#2 4 10 22 24 18 21
#3 6 12 24 27 21 24

#[[2]]
#  a  b  d  c  e  f
#1 2  8 20 21 15 18
#2 4 10 22 24 18 21
#3 6 12 24 27 21 24

data

df <- data.frame(a = 1:3, b = 4:6, c = 7:9, d = 10:12, e = 5:7, f = 6:8)
list_df <- list(df, df)

Why not make things simple and preserve column order? The following assumes that the data frame only 6 columns, and they all need to be multiplied.

l <- list(df,df)
lapply(l, function(x) x*c(2,2,3,2,3,3))

Output

[[1]]
  X1 X2 X3 X4 X5 X6
   2  4  9  8 15 18

[[2]]
  X1 X2 X3 X4 X5 X6
  2  4  9  8 15 18

Data

df <- data.frame(1,2,3,4,5,6)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM