Efficiently transform multiple columns of a data frame

后端 未结 3 597
孤街浪徒
孤街浪徒 2020-12-17 00:10

I have a data frame, and I want to transform all columns (say, take the logs or whatever) with columns that match a certain name. So in the example below, I want to take the

3条回答
  •  眼角桃花
    2020-12-17 00:35

    In the case of functions that will return a data.frame:

    cols <- c("X.1","X.2")
    df[cols] <- log(df[cols])
    

    Otherwise you will need to use lapply or a loop over the columns. These solutions will be slower than the solution above, so only use them if you must.

    df[cols] <- lapply(df[cols], function(x) c(NA,diff(x)))
    for(col in cols) {
      df[col] <- c(NA,diff(df[col]))
    }
    

提交回复
热议问题