[英]How to get an entire column from a table with multiple columns on a condition that the column contains a specific value in R
我在 R 中有一個簡單的表,其中包含 3 列(名為“countries_A”、“countries_B”和“countries_C”),每列包含 4 個國家/地區。 現在我想做的是編寫一個 function 在表中搜索特定國家,比如“意大利”,然后返回該國家所在列的所有元素作為向量或列表(除了那個特定的國家)。 因此,在我的示例中,作為“countries_B”列中的“Italy”以及瑞典、西班牙和瑞士,這意味着我將獲得一個包含“countries_B”列中除意大利以外的所有元素的單個向量,這意味着我將獲得“[瑞典、西班牙和瑞士]”作為答案。 我真的很感激任何幫助。 如果可能的話,我希望盡可能使用像 dtplyr 這樣的庫來對搜索進行矢量化。 下面,我附上了我的表格的屏幕截圖和 R 腳本以生成該表格。 提前謝謝了。
countries <- data.frame("countries_A" =
c('Belgium','Holland', 'France', 'Germany'),
"countries_B" = c('Sweden','Italy','Spain','Switzerland'),
"countries_C"= c('England','Denmark','Portugal','Hungary'))
讓我知道這是否對您有幫助:
find.country <- function(df, country){
df$ID <- seq.int(nrow(df))
df1 <-df %>%
pivot_longer(cols = -ID) %>%
filter(value == {country})
column.name <- df1$name
df2 <- df %>%
pivot_longer(cols = -ID) %>%
filter(name == column.name) %>%
filter(value != {country})
vector <- as.vector(df2$value)
return(vector)
}
find.country(df = countries, country = "Italy")
[1] "Sweden" "Spain" "Switzerland"
不太優雅:
get_vector = function(df_countries, country){
column = countries %>% mutate(across(everything(),
~if_else(country %in% .x, cur_column(), NULL))) %>%
mutate(var = coalesce(countries_A, countries_B, countries_C)) %>%
select(var) %>% slice(1) %>% pull
vector = countries %>% select(column) %>% filter(.data[[column]] != country) %>% pull %>% as.vector
return(vector)
}
get_vector(countries, 'Sweden')
> get_vector(countries, 'Sweden')
[1] "Italy" "Spain" "Switzerland"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.