gpt4 book ai didi

r - 如何删除数据框中特定列之前的所有列?

转载 作者:行者123 更新时间:2023-12-02 05:56:50 25 4
gpt4 key购买 nike

我想删除指定列之前的所有列。

示例数据:在 mpg 中,这些是按顺序排列的以下列名称:

names(mpg)

[1] "manufacturer", "model", "displ", "year", "cyl", "trans", "drv", "cty",

[9] "hwy", "fl", "class"

假设我想删除列“cyl”之前的所有列,我会这样做:

mpg[-(1:4)]

但在我的实际数据中,有时指定列(即cyl)之前的列数会发生变化。因此,不是总是在所需列 (cyl) 之前的 4 列(manufacturer, model, displ, year),有时是 3 或 7,等等。

如何调整此代码以确保包含“cyl”及其之后的所有列?

最佳答案

您可以使用 which 来获取正确的索引和使用它的子集。您需要减去 1,因为您不想删除 cyl 列。

如果您已经在使用 tidyverse 工具(这似乎很可能,因为您正在使用来自 ggplot2 的示例数据集),您也可以使用 dplyr 执行此操作: :select()tidyselect::last_col() 如下。语法是您可以通过 colnamea:colnameb 引用列选择,这将是从 colnameacolnameb 的所有列(包括在内)。 last_col 是对数据框中最后一列的引用,因为我们不会自动知道这里是什么。

remove_up_to <- function(df, colname){
col_i <- which(colnames(df) == colname) - 1
df[-(1:col_i)]
}

library(tidyverse)
remove_up_to(mpg, "cyl")
#> # A tibble: 234 x 7
#> cyl trans drv cty hwy fl class
#> <int> <chr> <chr> <int> <int> <chr> <chr>
#> 1 4 auto(l5) f 18 29 p compact
#> 2 4 manual(m5) f 21 29 p compact
#> 3 4 manual(m6) f 20 31 p compact
#> 4 4 auto(av) f 21 30 p compact
#> 5 6 auto(l5) f 16 26 p compact
#> 6 6 manual(m5) f 18 26 p compact
#> 7 6 auto(av) f 18 27 p compact
#> 8 4 manual(m5) 4 18 26 p compact
#> 9 4 auto(l5) 4 16 25 p compact
#> 10 4 manual(m6) 4 20 28 p compact
#> # ... with 224 more rows
mpg %>% select(cyl:tidyselect::last_col())
#> # A tibble: 234 x 7
#> cyl trans drv cty hwy fl class
#> <int> <chr> <chr> <int> <int> <chr> <chr>
#> 1 4 auto(l5) f 18 29 p compact
#> 2 4 manual(m5) f 21 29 p compact
#> 3 4 manual(m6) f 20 31 p compact
#> 4 4 auto(av) f 21 30 p compact
#> 5 6 auto(l5) f 16 26 p compact
#> 6 6 manual(m5) f 18 26 p compact
#> 7 6 auto(av) f 18 27 p compact
#> 8 4 manual(m5) 4 18 26 p compact
#> 9 4 auto(l5) 4 16 25 p compact
#> 10 4 manual(m6) 4 20 28 p compact
#> # ... with 224 more rows

reprex package 创建于 2018-08-07 (v0.2.0).

关于r - 如何删除数据框中特定列之前的所有列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51735495/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com