當名稱在資料框中匹配時,我想替換命名向量中的名稱(盡管可以轉換為串列)。在這里,我有一個名為的向量list1。然后,我有df一個ID與.list1new_namelist1
資料
list1 <- c(`3381` = 0.17492310894803, `3385` = 0.114350865502778, `3389` = 0.0761515760913618,
`3391` = 0.102018929027825, `3395` = 0.14140280849757, `3397` = 0.136809180022465
)
# 3381 3385 3389 3391 3395 3397
#0.17492311 0.11435087 0.07615158 0.10201893 0.14140281 0.13680918
df <- structure(list(ID = c(3389L, 3397L, 3391L, 3385L, 3381L, 3395L,
4400L), new_name = c(163, 429, 223, 49, 3, 360, 250)), row.names = c(NA,
-7L), class = c("tbl_df", "tbl", "data.frame"))
# ID new_name
# <int> <dbl>
#1 3389 163
#2 3397 429
#3 3391 223
#4 3385 49
#5 3381 3
#6 3395 360
#7 4400 250
預期產出
output <-c(`3` = 0.17492310894803, `49` = 0.114350865502778, `163` = 0.0761515760913618,
`223` = 0.102018929027825, `360` = 0.14140280849757, `429` = 0.136809180022465)
# 3 49 163 223 360 429
#0.17492311 0.11435087 0.07615158 0.10201893 0.14140281 0.13680918
我猜我可以使用MaporsetNames或其他東西,但我只是不確定,因為我不經常使用命名向量。我搜索了幾個帖子,但找不到類似的問題。
uj5u.com熱心網友回復:
簡單的
names(list1)=df$new_name[match(names(list1),df$ID)]
3 49 163 223 360 429
0.17492311 0.11435087 0.07615158 0.10201893 0.14140281 0.13680918
uj5u.com熱心網友回復:
我們還可以使用enframeand deframe:
library(tidyverse)
enframe(list1) %>%
mutate(name = ifelse(name %in% df$ID, deframe(df)[name], name)) %>%
deframe
# 3 49 163 223 360 429
#0.17492311 0.11435087 0.07615158 0.10201893 0.14140281 0.13680918
另一種選擇是left_join,然后選擇正確的列并再次使用deframe.
enframe(list1) %>%
mutate(name = as.numeric(name)) %>%
left_join(., df, by = c(name = "ID")) %>%
select(new_name, value) %>%
deframe
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/439690.html
上一篇:從字典值中獲取子字串
