我有一個資料框,其中包含測量員輸入的國家和年份資訊。我遇到的問題是可以選擇輸入多個國家/地區,人們以不同的格式輸入(例如,用空格、逗號或“和”分隔)。我有一個預定義的國家串列。我想要的是通過從預定義的國家串列中識別字串來計算每個國家每年出現的次數。所以這就是我的資料框的樣子。
Countries_predefined <- as.data.frame(c("Brazil", "Chile", "United States", "United Kingdom"))
colnames(Countries_predefined) <- "Country"
Surveyor_form <- as.data.frame(c("Brazil", "Brazil and United States", "United States United Kingdom", "Brazil, United Kingdom, United States"))
colnames(Surveyor_form) <- "Country"
Surveyor_form$Year <- c("1999", "1999", "2000", "2000")
我希望最終輸出看起來像:
Country 1999 2000
Brazil 2 1
Chile 0 0
United States 1 2
United Kingdom 0 2
我在這個問題R dplyr: Filter data by multiple Regex expressions defined by vector how to filter a data frame by a certain string 中讀到,我已經成功使用下面的 regex.escape 函式來識別是否識別了某些單詞,但可以'不認為我可以如何應用它來計算每年的國家數量。
regex.escape <- function(string) {
gsub("([][{}() *^$|\\\\?.])", "\\\\\\1", string)
}
uj5u.com熱心網友回復:
你可以試試。
t(table(stack(Map(function(x) Surveyor_form$Year[grep(x,Surveyor_form$Country)],
Countries_predefined$Country))))
# values
#ind 1999 2000
# Brazil 2 1
# Chile 0 0
# United States 1 2
# United Kingdom 0 2
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/480410.html
