【问题标题】:Drop columns of a dataframe using inverse index使用反向索引删除数据帧的列
【发布时间】:2021-08-18 06:55:25
【问题描述】:

以下函数接受一个数据框和一个列索引列表作为参数,并将它们打印出来。

testfunc1 <- function (df, cols){
  print(df[cols])
}

例如,以下函数调用打印出数据帧的第 3 列和第 4 列

testfunc1(subset(iris, Species == "setosa")[,1:4], -c(1,2))

不过,我也在尝试保持函数参数不变,并弄清楚如何打印列索引的倒数。

例如我想要和上面一样的函数调用,在不添加新参数的情况下也打印出数据框的第一列和第二列

我已将索引乘以 -1 以反转它们,但有更好的方法吗?

testfunc1 <- function (df, cols){
      print(df[cols])
      print(df[-1*cols])
}

*附言- 我正在尝试仅使用基础 R 来执行此操作

【问题讨论】:

  • 我觉得不错。
  • 看起来很简单,也许没有更好的方法。创建该函数时您的意图是什么?

标签: r


【解决方案1】:

如果您不介意在list 中打印结果数据帧,您可以尝试

testfunc2 <- function(df, col){ 
    list(df[col], df[-col])
}

testfunc2(subset(iris, Species == "setosa")[, 1:4], -c(1, 2))

我发现在您的示例中,testfunc2 平均比 testfunc1 快​​十倍以上。

library(microbenchmark)
microbenchmark(testfunc1(subset(iris, Species == "setosa")[,1:4], -c(1,2)), testfunc2(subset(iris, Species == "setosa")[,1:4], -c(1,2)))

# Unit: microseconds
#                                                          expr    min     lq     mean median      uq
# testfunc1(subset(iris, Species == "setosa")[, 1:4], -c(1, 2)) 2651.2 2895.7  5377.846 3839.6 6034.20
# testfunc2(subset(iris, Species == "setosa")[, 1:4], -c(1, 2))  106.3  137.4   306.929  206.2  282.65
#     max neval cld
# 19966.6   100   b
#  2859.5   100  a

除了更短的执行时间之外,将结果数据帧存储在列表中的另一个优点是它可以更轻松地访问打印数据帧的不同部分。

在前面的例子中,df[col] 可以使用testfunc2(...)[[1]] 访问,而df[-col] 使用testfunc2(...)[[2]]

【讨论】:

    猜你喜欢
    • 2018-05-14
    • 2015-04-24
    • 1970-01-01
    • 2023-03-12
    • 2021-09-01
    • 2019-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多