[英]Subset tibble based on column sums, while retaining character columns
我覺得這是一個非常愚蠢的問題,但我也無法找到解決方案
我有一個小標題,其中每一行都是一個樣本,第一列是一個包含樣本ID的字符變量,所有后續列都是帶有數字變量的變量。
例如:
id <- c("a", "b", "c", "d", "e")
x1 <- rep(1,5)
x2 <- seq(1,5,1)
x3 <- rep(2,5)
x4 <- seq(0.1, 0.5, 0.1)
tb <- tibble(id, x1, x2, x3, x4)
我想對此進行子集化,以僅包括總和大於5的列和id列。 使用舊的數據框結構,我知道以下工作方式:
df <- as.data.frame(tb)
df2 <- cbind(df$id, df[,colSums(df[,2:5])>5)
colnames(df2)[1] <- "id"
但是,當我嘗試以這種方式對子集進行細化時,出現錯誤消息:
Error: Length of logical index vector must be 1 or 5, got: 4
有誰知道如何在不轉換為舊數據幀格式的情況下完成此任務? 最好不要創建缺少id變量的中間小標題,因為將我的id與數據分開只是在路上麻煩。
謝謝!
# install.packages(c("tidyverse"), dependencies = TRUE)
library(tibble)
df <- tibble(id = letters[1:5], x1 = 1, x2 = 1:5, x3 = 2, x4 = seq(.1, .5, len = 5))
### two additional examples of how to generate the Tibble data
### exploiting that its arguments are evaluated lazily and sequentially
# df <- tibble(id = letters[1:5], x1 = 1, x2 = 1:5, x3 = x1 + 1, x4 = x2/10)
# df <- tibble(x2 = 1:5, id = letters[x2], x3 = 2, x1 = x3-1, x4 = x2/10) %>%
# select(id, num_range("x", 1:4))
base R
解決方案,請參閱。 HubertL的上述評論 ,
### HubertL's base solution
df[c(TRUE,colSums(df[2:5])>5)]
#> # A tibble: 5 x 3
#> id x2 x3
#> <chr> <int> <dbl>
#> 1 a 1 2
#> 2 b 2 2
#> 3 c 3 2
#> 4 d 4 2
#> 5 e 5 2
dplyr
解決方案,請dplyr
David Klotz的評論 ,
### Klotz's dplyr solution
library(dplyr)
df %>% select_if(function(x) is.character(x) || sum(x) > 5)
#> # A tibble: 5 x 3
#> id x2 x3
#> <chr> <int> <dbl>
#> 1 a 1 2
#> 2 b 2 2
#> 3 c 3 2
#> 4 d 4 2
#> 5 e 5 2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.