【问题标题】:R: Match specific elements from a list of data frames and create new data frameR:匹配数据框列表中的特定元素并创建新数据框
【发布时间】:2019-04-26 17:46:31
【问题描述】:

让我们有一个数据框列表:

df1 <- data.frame(V1=c("a", "b", "c"),V2=c("d", "e","f"), V3=c("g","h","i"),V4=c("j","k","l"))
df2 <- data.frame(V1=c("m","n"), V2=c("o","p"), V3=c("q","r"))
l <-list(df1, df2)
> l
[[1]]
  V1 V2 V3 V4
1  a  d  g  j
2  b  e  h  k
3  c  f  i  l

[[2]]
  V1 V2 V3
1  m  o  q
2  n  p  r

此外,我们还有一个向量:

ele <- c("a","b","e","g","i","m","p","s","t")

我想通过匹配向量ele 和列表l 中的元素来获得一个新的数据框。数据框应该具有来自向量的匹配元素的列名,以及来自列表中匹配元素的元素。 例如:

df3 <-data.frame(a="d",b='e',e="h",g="j",i="l",m="o",p="r")
> df3
  a b e g i m p
1 d e h j l o r

您可能会注意到没有特定的匹配模式。

【问题讨论】:

    标签: r list dataframe data-manipulation


    【解决方案1】:

    也许某处有更好的解决方案,但这是一种可能性:

    library(tidyverse)
    library(magrittr)
    
    l %<>%
      map(~ t(.x) %>% 
            as_tibble() %>% 
            flatten_chr())
    
    
    ele %>%
      map(~ map(l, equals, .x)) %>% 
      map_chr(~ {
        lgl <- map_lgl(.x, any)
        if (!any(lgl)) {
          NA
        } else {
          lgl_idx <- min(which(lgl))
          lgl     <- l[[lgl_idx]]
          lgl[min(which(.x[[lgl_idx]])) + 1]
        }
      }) %>%
      set_names(ele) %>%
      na.omit()
    

    需要更多的异常处理(例如当向量等于最后一列中的元素时),但它适用于您给出的示例。

      a   b   e   g   i   m   p 
    "d" "e" "h" "j" "l" "o" "r" 
    

    【讨论】:

    • 这对我来说是一个相当复杂的例子,但它在给定的例子和我的工作数据集中都能正常工作。谢谢!起首低音!
    【解决方案2】:

    您可以使用which 微调与参数匹配的元素,然后向其添加一个向量(在本例中为c(0,1))。

    ele_list = as.list(ele)
    names(ele_list) = ele
    unlist(lapply(ele_list, function(e) df1[which(df1 == e, arr.ind = TRUE)  + c(0, 1)]))
    
      a   b   e   g   i 
    "d" "e" "h" "j" "l" 
    

    我只是为df1 做的,你可以为两者运行第三行,然后合并向量并转换为数据帧。

    【讨论】:

    • 能否提供l列表的功能?
    猜你喜欢
    • 2015-04-21
    • 2022-07-29
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 2023-03-18
    • 1970-01-01
    • 2019-06-26
    • 2020-04-28
    相关资源
    最近更新 更多