所以假設我想創建一個這樣的串列:
x <- c(John=23, Mary=33)
有沒有辦法用變數替換鍵名。類似的東西(但由于明顯的原因,這不起作用:
husband <- 'John'
wife <- 'Mary'
x <- c(husband=23, wife=33)
# Expected output: c(John=23, Mary=33)
換句話說,在上面的例子中,有沒有辦法husband用John等替換?
uj5u.com熱心網友回復:
您可以使用setNames.
husband <- 'John'
wife <- 'Mary'
setNames(c(23, 33), c(husband, wife))
# John Mary
# 23 33
或與dplyr-
library(dplyr)
unlist(lst(!!husband := 23, !!wife := 33))
uj5u.com熱心網友回復:
在基礎 R 中:
一種適用于所有名稱的方法,并從變數名稱中獲取:
names(x) <- Map(function(x) eval(parse(text=x)), names(x))
> x
John Mary
23 33
>
uj5u.com熱心網友回復:
我們可以用 dput
x <- c(John=23, Mary=33)
husband <- 'John'
wife <- 'Mary'
result <- dput(x)
輸出:
c(John = 23, Mary = 33)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/324574.html
標籤:r
