我有一个如下所示的列表:
$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)
}
但是,当我在名称全部保持不变后检查列表时
最佳答案
我希望您正在寻找这个:
#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"
关于使用数据框按键重命名列表元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64360593/