2017-05-19 5 views
0

文字列を保持したまま、列の合計に基づいていますが、それぞれの行がどこにあるか私がtibbleを持っている溶液のいずれかサブセットtibble私はこれはかなり愚かな問題である感じを持っている

を見つけることができませんでした最初の列はサンプル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) 

Iは5より大きい和、及びidカラムと列のみを含むようにこのサブセットたいです。古いデータフレーム構造で、私は次のように働いていた知っている:私はtibbleでこのようにサブセットしようとすると、

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とデータを分離するのは、ちょっとしたトラブルを求めているからです。

ありがとうございます!

+0

'のDF [C(TRUE、colSums(2 [DF:5])> 5)このような' – HubertL

答えて

0
# 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解決策、cf. HubertL's comment above

### 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溶液、CF David Klotz's comment

### 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 
+1

何か: DF %>%select_if(function(x)is.character(x)|| sum(x)> 5) –

関連する問題