【问题标题】:R: Applying functions to multiple named columns in a data frame - improvements?R:将函数应用于数据框中的多个命名列 - 改进?
【发布时间】: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 强制到数据帧?

这里有什么改进吗?似乎我缺少一些关于各种“应用”功能如何工作的基本知识。

【问题讨论】:

    标签: r dataframe apply


    【解决方案1】:

    您的最后两次尝试非常接近。这是一个有效的简单版本:

    f[cols] <- lapply(f[cols], convert.f)
    

    产生:

    'data.frame':   2 obs. of  5 variables:
     $ X1: Factor w/ 1 level "2": 1 1
     $ X2: Factor w/ 1 level "1": 1 1
     $ X3: num  3 3
     $ XA: Factor w/ 1 level "a": 1 1
     $ X4: Factor w/ 1 level "4": 1 1
    

    注意:

    for (col in cols) {
      f[col] <- convert.f(f[, col])
    }
    

    也有效。您的版本不起作用,因为f[col] 返回一个数据框,而不是一个向量,所以您的is.numeric(v) 测试失败并且convert.f 返回插入到f[col] 中的未更改的单列数据框,所以它看起来像@987654328 @ 没有改变。通过使用[ 的两个参数版本,drop 参数开始起作用,f[, col] 返回一个向量而不是一列数据框。

    【讨论】:

      猜你喜欢
      • 2021-07-11
      • 2021-04-19
      • 2018-07-29
      • 1970-01-01
      • 1970-01-01
      • 2021-09-03
      • 2021-08-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多