【发布时间】:2016-03-15 00:54:33
【问题描述】:
我有一个包含许多列的数据框。我想对这些列中的许多列进行重复操作,并用名称进行了标记。
例如:
convert.f <- function(v) {
if (is.numeric(v) && !is.factor(v)) {
v <- as.factor(v)
}
return (v)
}
f <- data.frame(X1=rep(2,2),X2=rep(1,2), X3=rep(3,2), XA=rep('a',2), X4=rep(4,2))
cols <- c('X1', 'X2', 'X4')
# Now, I want to apply 'convert.f' to cols X1, X2, and X4 only and store it in the
# original data frame.
以下所有尝试都不正确。
# Doesn't seem to return a data frame I can use...
apply(f[, cols], 2, convert.f)
# Same as above I think
f2 <- sapply(f[, cols], convert.f)
# Even if I coerce it, I get some problems
f2 <- data.frame(f2)
f2$X1 # Error
# Appears to have no change in the data frame
ddply(f, cols, convert.f)
# This doesn't seem to save the results back into the frame
for (col in cols) {
f[col] <- convert.f(f[col])
}
一个可能的解决方案:
# Here's the best way I've found so far but it seems inefficient.
f3 <- data.frame(lapply(f[,cols], convert.f))
f[, names(f3)] <- f3
# However, if I do this in a function and return f, it doesn't seem to make my changes stick. Still trying to figure that one out.
为什么最后一个适用于 lapply 强制到数据帧?
这里有什么改进吗?似乎我缺少一些关于各种“应用”功能如何工作的基本知识。
【问题讨论】: