使用数据框按键重命名列表元素

Renaming list elements by key with dataframe

我有一个如下所示的列表:

$fec9
[1] "yes"

$`39c1`
[1] "no"

$d387
[1] "yes"

$`0065`
[1] "yes"

和一个具有与列表元素匹配的键的数据框:

dataframe <- data.frame(key = c('39c1', 'fec9', 'p731' '0065', 'd387'),
                        label = c('trash', 'wash car', 'cook dinner', 'mow lawn', 'vacuum'))

我正在尝试将列表中的每个元素重命名为相应键的标签,但数据框的顺序与列表的顺序不同,并且数据框中的一些键没有出现在列表中。目前我正在尝试:

for(i in names(list)){
  names(list[i]) <- dataframe %>% filter(key == names(list[i])) %>% select(label)
}

但是当我检查列表时,名字都保持不变

假设 data.frame 的列是 character,那么我们得到 'list' 的 namesintersecting 元素和 'key' 并使用它为 list 值分配相应的 'label'

nm1 <- intersect(names(list), dataframe$key)
list[nm1] <- dataframe$label[dataframe$key %in% nm1]

数据

list <- list(fec9 = 'yes', `39c1` = 'no', 'd387' = 'yes', `0065` = 'yes')
dataframe <- data.frame(key = c('39c1', 'fec9', 'p731', '0065', 'd387'),  
           label = c('trash', 'wash car', 'cook dinner', 'mow lawn', 'vacuum'))

我希望你正在寻找这个:

#method 1
#get common key from dataframe
df <- df[df$key %in% names(list), ]
list <- list[df$key] #getting the same order as of dataframe
names(list) <- df$label

#method 2
#if you want to preserve the order of labels: 
df <- df[df$key %in% names(list), ]
row.names(df) <- df$key
names(list) <- df[names(list), ]$label

数据

list <- list(fec9 = 'yes', `39c1` = 'no', 'd387' = 'yes', `0065` = 'yes')
df <- data.frame(key = c('39c1', 'fec9', 'p731', '0065', 'd387'),  
                        label = c('trash', 'wash car', 'cook dinner', 'mow lawn', 'vacuum'), stringsAsFactors = FALSE)

第二种方法的输出:

$`wash car`
[1] "yes"

$trash
[1] "no"

$vacuum
[1] "yes"

$`mow lawn`
[1] "yes"

这是使用 merge + stack + setNames

的基础 R 选项
with(
  merge(stack(lst), df, by.x = "ind", by.y = "key"),
  setNames(as.list(values), label)
)

这给出了

$`mow lawn`
[1] "yes"

$trash
[1] "no"

$vacuum
[1] "yes"

$`wash car`
[1] "yes"

数据

> dput(lst)
list(fec9 = "yes", `39c1` = "no", d387 = "yes", `0065` = "yes")

> dput(df)
structure(list(key = c("39c1", "fec9", "p731", "0065", "d387"
), label = c("trash", "wash car", "cook dinner", "mow lawn",
"vacuum")), class = "data.frame", row.names = c(NA, -5L))