[英]How can I remove all columns before a specific column in a dataframe?
我想刪除指定列之前的所有列。
示例數據:以mpg
,這些列順序如下:
names(mpg)
[1] "manufacturer", "model", "displ", "year", "cyl", "trans", "drv", "cty",
[9] "hwy", "fl", "class"
假設我要刪除列“ cyl
”之前的所有列,我會這樣做:
mpg[-(1:4)]
但在我的實際數據中 ,有時候指定列(即cyl
)之前的列數會發生變化。 因此,不是4列( manufacturer, model, displ, year
)總是在所需的列( cyl
)之前,有時會有3或7等。
如何調整此代碼以確保包含“ cyl
”之后的所有列?
您可以使用which
來獲取正確的索引和子集。 您需要減1,因為您不想刪除cyl
列。
如果您已經在使用tidyverse
工具(這似乎可能因為您使用的是ggplot2
的示例數據集),您也可以使用dplyr::select()
和tidyselect::last_col()
,如下所示。 語法是您可以通過colnamea:colnameb
引用列選擇,這將是從colnamea
到colnameb
所有列。 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包創建於2018-08-07(v0.2.0)。
其他方法可能更快更清晰。 這是一個模糊的方法:
mpg[ !cumall(!("cyl" == colnames(mpg))) ]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.