2017-06-20 10 views
1

アルファベットと数字の文字列を含む単一の列に基づいて、データフレームオブジェクトを作成しました。
数字文字とgrepl関数との一致に基づいて行数を数えます。数値を含む行の一致とカウント

私のダミーのデータセットには、1911年、1896年、1906年の3つの異なる文字列を含む6行があります。 私の実際のデータセットには、30の異なる文字列と30 000行があります。 dplyr

library(dplyr) 
dataset2 <- dataset %>% 
filter(grepl("1911", dataset)) %>%  # filtering with grepl 
summarise (total_1911= length(dataset)) # summarise n rows 

と「1911」のためのn行を計算

dataset <- c("Lorem ipsum dolor sit amet 1911", "consectetur adipiscing elit 1911", "Pellentesque at pellentesque nulla 1906", "Aenean eget feugiat ligula 1906", "Aenean eget feugiat ligula. Fusce vulputate 1911", "dui eget fermentum tristique 1896") 
dataset <- as.data.frame(dataset) 

だから私は、私は繰り返しは、各数字のために、このコマンドを作るために避けるようにすることができますか?私の予想出力

(基R又はdplyrで):

date n 
1911 3 
1906 2 
1896 1 

答えて

1

我々は、要素(n())の周波数を取得する変数とsummariseをグループ化するようにそれを使用して、数値部分を抽出

library(tidyverse) 
dataset %>% 
    group_by(date = str_extract(dataset, "\\d+")) %>% 
    summarise(n = n()) 
+1

それは本当に良いと非常に明確です。 – Wilcar

2

別のオプション:

count(dataset, date = paste0("total_", gsub("\\D+", "", dataset))) 
## A tibble: 3 x 2 
#  date  n 
#  <chr> <int> 
#1 total_1896  1 
#2 total_1906  2 
#3 total_1911  3 

gsubすべての非数字文字を削除し、それをtotal_と一緒に貼り付けます。一意の日付あたりの行数を取得するには、countを使用します。

2

ベースRでは、uniqueの数字をすべて列から抽出し、greplを使用して各列の出現を見つけることでこれを実行できます。基地Rで

nums <- unique(gsub("[^0-9]", "", dataset$dataset)) 
sapply(nums, function(x) sum(grepl(x, dataset$dataset))) 


# 1911 1906 1896 
# 3 2 1 
1

、我々はtablegsubの出力を供給できます。

table(gsub("[^0-9]+", "", dataset$dataset)) 

1896 1906 1911 
    1 2 3 

又はdata.frameなどの変数名とsetNamesを使用して追加。

setNames(data.frame(table(gsub("[^0-9]+", "", dataset$dataset))), c("date", "n")) 
    date n 
1 1896 1 
2 1906 2 
3 1911 3 
関連する問題