我正在處理一個資料集,該資料集顯示每年存在哪些變數。我需要一個函式來指定特定年份,然后回傳所有這些年份中出現的變數。換句話說,如果指定年份“70”和“90”,我希望函式在這兩年中找到所有帶有變數的行(基于變數名,而不是列名)。
這篇文章給了我將所有年份列粘貼在一起的想法,所以我只需要將 grepl() 應用于一列。正如你在下面看到的,我能找到匹配所有年份的唯一方法是運行for回圈兩次,一次是識別年份中的任何匹配,第二次是洗掉任何非匹配。有沒有更簡單的方法來做到這一點?
我對 R 比較陌生(這是我在這里的第一篇文章!)所以我很感激任何想法。
# testing data frame (actual data has many more items and years)
item <- c("ABC", "DEF", "GHI", "JKL", "MNO", "PQR", "STU")
x1970 <- c("abc70", "70def", "gh70i", "jkl70", "", "70pqr", "stu70x")
x1980 <- c("abc80", "80def", "", "", "", "80pqr", "stu80x")
x1990 <- c("abc90", "90def", "", "", "90mno90", "90pqr", "")
x2000 <- c("", "00def", "gh00i", "jkl00", "00mno00", "00pqr", "")
df <- data.frame(item, x1970, x1980, x1990, x2000)
df
item x1970 x1980 x1990 x2000
1 ABC abc70 abc80 abc90
2 DEF 70def 80def 90def 00def
3 GHI gh70i gh00i
4 JKL jkl70 jkl00
5 MNO 90mno90 00mno00
6 PQR 70pqr 80pqr 90pqr 00pqr
7 STU stu70x stu80x
year_filter_test <- function(data, year)
{
# paste all year columns together in "search_columns" so I can apply grepl() to that one column
data2 <- data %>% mutate(search_columns = paste(x1970, x1980, x1990, x2000) )
# create "include" column which will be TRUE if I want to include this row
data2$include <- rep( "", nrow(data2))
# loop through each year, making include column TRUE if there's a match on ANY year
for (i in year)
{ data2$include [ grepl(i, data2$search_columns) ] <- TRUE
}
# loop through each year again, making include column FALSE if there's NOT a match on ANY year
# the effect of these two loops is to only include columns that match ALL years
for (i in year)
{ data2$include [ !grepl(i, data2$search_columns) ] <- FALSE
}
selected.years <- data2 %>% filter(include==TRUE)
return(selected.years)
}
uj5u.com熱心網友回復:
像這樣的東西?
library(dplyr)
library(tidyr)
my_function <- function(df, x){
df %>%
pivot_longer(
cols=-item
) %>%
mutate(year = parse_number(value)) %>%
pivot_wider(
names_from = name
) %>%
filter(year == {{x}})
}
my_function(df, c("70", "90"))
item year x1970 x1980 x1990 x2000
<chr> <dbl> <chr> <chr> <chr> <chr>
1 ABC 70 abc70 NA NA NA
2 DEF 70 70def NA NA NA
3 GHI 70 gh70i NA NA NA
4 MNO 90 NA NA 90mno90 NA
5 PQR 90 NA NA 90pqr NA
uj5u.com熱心網友回復:
使用 across
library(dplyr)
library(stringr)
my_func <- function(dat, years) {
dat %>%
filter(across(num_range('x', years), ~ str_remove_all(., "\\d ") == tolower(item)))
}
-測驗
> my_func(df, c('1970', "1990"))
item x1970 x1980 x1990 x2000
1 ABC abc70 abc80 abc90
2 DEF 70def 80def 90def 00def
3 PQR 70pqr 80pqr 90pqr 00pqr
uj5u.com熱心網友回復:
我們可以用dplyr用rowwise,if_all以及stringr::str_detect:
library(dplyr)
library(stringr)
my_func<-function(df, years){
df%>%
rowwise()%>%
mutate(index=if_all(num_range('x', years), ~str_detect(tolower(.x), tolower(item))))
}
my_func(df, c(1970, 1990))
# A tibble: 7 × 6
# Rowwise:
item x1970 x1980 x1990 x2000 index
<chr> <chr> <chr> <chr> <chr> <lgl>
1 ABC "abc70" "abc80" "abc90" "" TRUE
2 DEF "70def" "80def" "90def" "00def" TRUE
3 GHI "gh70i" "" "" "gh00i" FALSE
4 JKL "jkl70" "" "" "jkl00" FALSE
5 MNO "" "" "90mno90" "00mno00" FALSE
6 PQR "70pqr" "80pqr" "90pqr" "00pqr" TRUE
7 STU "stu70x" "stu80x" "" "" FALSE
我們可以輕松地使用新的邏輯列來執行過濾操作。
如果我們想直接過濾,我們可以修改函式:
my_filter<-function(df, years){
df%>%
rowwise()%>%
filter(if_all(num_range('x', years), ~str_detect(tolower(.x), tolower(item))))
}
my_filter(df=df, years=c(1970, 1990))
# A tibble: 3 × 5
# Rowwise:
item x1970 x1980 x1990 x2000
<chr> <chr> <chr> <chr> <chr>
1 ABC abc70 abc80 abc90 ""
2 DEF 70def 80def 90def "00def"
3 PQR 70pqr 80pqr 90pqr "00pqr"
uj5u.com熱心網友回復:
這有點不清楚,但聽起來您希望將 data.frame 中的值與包含年份的最后 2 位數字的函式相匹配,而不是查看也包含年份的列名。
如果這是正確的,您可以使用rowSums為給定行中的字符值找到的部分匹配項相加。如果總和與您要搜索的“年”數相同,則該行將保留在您的過濾器中。
library(tidyverse)
year_filter <- function(data, years) {
data %>%
filter(rowSums(
sapply(select(., starts_with("x")),
function(x) grepl(paste(years, collapse = "|"), x))
) == length(years))
}
year_filter(df, c("70", "90"))
輸出
item x1970 x1980 x1990 x2000
1 ABC abc70 abc80 abc90
2 DEF 70def 80def 90def 00def
3 PQR 70pqr 80pqr 90pqr 00pqr
編輯:鑒于每年可能有多個列,應在函式中考慮列年份。
這是一個替代方案。首先,允許函式使用完整的 4 位數年份,并創建一個變數來存盤最后 2 位數以進行搜索。
將您的資料放入長格式,并從列名中提取年份(這樣 1970.a 和 1970.b 將被視為 1970)。
然后,按 data.frame 的每一行分組,首先通過包含與年份的最后 2 位數字匹配的匹配項進行過濾,然后確保在該行中找到所有年份。最后,您將根據過濾器后剩余的資料回傳行號。
year_filter <- function(data, years) {
last2dig_yrs <- substr(years, nchar(years) - 1, nchar(years))
match_rows <- data %>%
mutate(rn = row_number()) %>%
pivot_longer(cols = -c(item, rn)) %>%
mutate(year = parse_number(name)) %>%
group_by(rn) %>%
filter(grepl(paste(last2dig_yrs, collapse = "|"), value)) %>%
filter(all(years %in% year)) %>%
distinct(rn) %>%
pull(rn)
return(data[match_rows,])
}
我用 1970.a 和 1970.b 列創建了示例資料。
示例資料
df <- structure(list(item = c("ABC", "DEF", "GHI", "JKL", "MNO", "PQR",
"STU"), x1970.a = c("abc70", "70def", "gh70i", "jkl70", "", "70pqr",
"stu70x"), x1970.b = c("zxc70", "def", "gh70i", "70d", "70x",
"", "stu70x"), x1980 = c("abc80", "80def", "", "", "", "80pqr",
"stu80x"), x1990 = c("abc90", "90def", "", "", "90mno90", "90pqr",
""), x2000 = c("", "00def", "gh00i", "jkl00", "00mno00", "00pqr",
"")), class = "data.frame", row.names = c(NA, -7L))
year_filter(df, c("1970", "1990"))
輸出
item x1970.a x1970.b x1980 x1990 x2000
1 ABC abc70 zxc70 abc80 abc90
2 DEF 70def def 80def 90def 00def
5 MNO 70x 90mno90 00mno00
6 PQR 70pqr 80pqr 90pqr 00pqr
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/338036.html
