2017-10-23 22 views
-1

データフレーム内の行が特定の文字で始まる方法を見つける方法がわかりません。特定の文字で始まる行の数を調べる方法は?

たとえば、

mtcars 
       mpg cyl disp hp drat wt ... 
Mazda RX4  21.0 6 160 110 3.90 2.62 ... 
Mazda RX4 Wag 21.0 6 160 110 3.90 2.88 ... 
Datsun 710 22.8 4 108 93 3.85 2.32 ... 

私はどのように多くの車を知りたいあなたは

sum(startsWith(rownames(mtcars), "M")) 
# [1] 10 

その他の少ない効率的な可能性を含んで行うことができます

答えて

4

'M'

おかげ文字で始まる

sum(grepl("^M", rownames(mtcars))) 
# [1] 10 
length(grep("^M", rownames(mtcars))) 
# [1] 10 
sum(regexpr("^M", rownames(mtcars)) == 1L) 
# [1] 10 
sum(substr(rownames(mtcars), 1, 1) == "M") 
# [1] 10 
0

Anothe rこれを行う良い方法は、stringrパッケージを使用することです。

library(stringr) 
str_view(rownames(mtcars),'^M') # to see all results or 
str_view(rownames(mtcars),'^M', match = T) # to see only the match results 
関連する問題