【问题标题】:How to return the names of a list if the index from two list matches? (R)如果两个列表中的索引匹配,如何返回列表的名称? (右)
【发布时间】:2022-06-12 02:57:32
【问题描述】:

我有一个数据框列 (df$source_index),其中包含 100 个索引属于 1-17 的 obs,另一个列表 (list_df) 的名称和索引从 1-17 相同。如何在此数据框中创建(变异)一列,只要 df 列中的索引(df$source_index)和列表的索引(list_df)匹配(相同的值),它返回列表名称?

df

dput(df)

structure(list(value = c(A,B,C,D,E,F,....N), source_index = c(1,1,1,2,2,3..17)), .Names = c("value ", 
"source_index"), row.names = c(NA, 17L), class = "data.frame")

    #   value source_index    
    # 1  A        1    
    # 2  B        1     
    # 3  C        1   
    # 4  D        2   
    # 5  E        2    
    # 6  F        3
    # .  . .
    # 17  N       17
     

具有索引 1-17 和 17 个元素的大型命名列表 list_df

list[17]
# name    Type    Value 
  apple char[5]   apple is red..
  orange char[8]  orange is sweet..
  ....
1st element: list_df[["apple"]]
2nd element: list_df[["orange"]]
...
17th element: list_df[["bana"]]

在 df 中具有新 col 的所需输出 df

    #   value source_index new col 
    # 1  A       1        apple  
    # 2  B       1        apple
    # 3  C       1        apple 
    # 4  D       2        orange
    # 5  E       2        orange
    # 6  F       3        orange
    # .  . . 
    # 17  N 17            bana

我尝试了 match(df$source_index, names(list_df)) 或 seq_along(list_df) 但它返回了所有 NA。

【问题讨论】:

  • 能否请您使用dput 作为您的data.frame 和列表让我们帮助您?

标签: r


【解决方案1】:

你可以这样做:

df %>% mutate(new_col = names(list_df)[source_index])

输出(前 10 行):

   value source_index new_col
1      W            1       a
2      V            1       a
3      M            1       a
4      H            1       a
5      Z            1       a
6      V            2       b
7      J            2       b
8      F            2       b
9      Y            3       c
10     B            3       c

输入:

set.seed(123)

df = data.frame(value = sample(LETTERS,100, replace=T), source_index= sample(1:17, 100, replace=T)) %>% arrange(source_index)

list_df =as.list(1:17)
names(list_df) <- letters[1:17]

【讨论】:

    猜你喜欢
    • 2018-07-08
    • 1970-01-01
    • 2021-07-18
    • 2020-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-09
    • 1970-01-01
    相关资源
    最近更新 更多