我想使用它們名稱的向量來系結相同維度的向量。
例如我想從
a <- c(2, 5, NA, NA, 6, NA)
b <- c(NA, 1, 3, 4, NA, 8)
矩陣使用 cbind(a,b)
a b
[1,] 2 NA
[2,] 5 1
[3,] NA 3
[4,] NA 4
[5,] 6 NA
[6,] NA 8
但是從環境物件名稱的向量中呼叫變數,例如 vectornames <- c("a","b")
我上次嘗試失敗 cbind(for(i in vectornames) get(i))
uj5u.com熱心網友回復:
你想sapply/這里lapply的get功能。例如:
a <- c(2, 5, NA, NA, 6, NA)
b <- c(NA, 1, 3, 4, NA, 8)
nmes <- c("a", "b")
# Apply get() to each name in the nmes vector
# Then convert the resulting matrix to a data frame
as.data.frame(sapply(nms, get))
a b
1 2 NA
2 5 1
3 NA 3
4 NA 4
5 6 NA
6 NA 8
從技術上講,您可以使用 來做到這一點cbind,但它更尷尬:
# Convert the vector of names to a list of vectors
# Then bind those vectors together as columns
do.call(cbind, lapply(nms, get))
uj5u.com熱心網友回復:
我們可以使用mget“獲取”串列,然后"loop-unlist"使用sapply和function(x) x或[創建矩陣
sapply(mget(vectornames), \(x) x)
#OR
sapply(mget(vectornames), `[`)
a b
[1,] 2 NA
[2,] 5 1
[3,] NA 3
[4,] NA 4
[5,] 6 NA
[6,] NA 8
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/350426.html
