2017-06-20 50 views
1

我有一個基於單個列的數據框對象,其中包含字母和數字字符的字符串。
我想根據數字字符與grepl函數的匹配數來計算行數。包含數字字符的匹配和計數行

在我的啞數據集中,我有6行包含3個不同的數字字符序列的字符串:1911,1896和1906. 在我的真實數據集中,我有30個不同的數字字符序列和30 000行。

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) 

計算爲「1911年」 n行與dplyr

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

所以我我可以讓一個迭代,以避免使這個命令對每個數字字符? (在基R或dplyr)

我的預期輸出:

date n 
1911 3 
1906 2 
1896 1 

回答

1

我們提取的數字部分,用其作爲分組變量和summarise得到元件的頻率(n()

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找到列中每個數字的出現。

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


# 1911 1906 1896 
# 3 2 1 
1

在基R,我們可以的gsub輸出饋送到table

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 
相關問題