Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
523 views
in Technique[技术] by (71.8m points)

r - Efficiently transform multiple columns of a data frame

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 log of X.1 and X.2, but not Y or Z.1.

df <- data.frame(
  Y = sample(0:1, 10, replace = TRUE),
  X.1 = sample(1:10),
  X.2 = sample(1:10),
  Z.1 = sample(151:160)
)

# option 1, won't work for dozens of fields
df$X.1 <- log(df$X.1)
df$X.2 <- log(df$X.2)

Is there a good, efficient way to do this when the dataframe is several gigabtyes?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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]))
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...