簡體   English   中英

將向量與類似名稱相結合

[英]Combining vectors with analogous names

我不熟悉R代碼,我試圖解決這個問題但沒有成功。 請幫我!

如果我有這種載體

> x1 <- c(5,7,9)
> x2 <- c(6,3,4)
....
> xn <- c(1,2,3) 

我想把它們結合起來

結果< - cbind(x1,x2,...,xn)

怎么說這個x1,x2,...,xn

謝謝!

您可以將ls與pattern參數一起使用

x.data <- ls(pattern='^x.?')

這將返回可與getsapply一起使用的名稱列表

sapply(x.data, get)
#  x1 x2 xn
# [1,]  5  6  1
# [2,]  7  3  2
# [3,]  9  4  3

盡管可以解決這個問題,但真正的解決方案可能是使用另一種方法來存儲您的向量。 你是怎么得到它們的?

通常情況下,當您有多個向量時,最好將列表結構中的向量作為單獨的全局變量。

這是一種方式

x <- list(x1 = c(5,7,9), x2=c(6,3,4), xn=c(1,2,3))

x$x2 # the x2 vector
str(x) # prints an overview of x

# combine them into a matrix
do.call(cbind, x)

這是從文件到列表中讀取一堆向量的一種方法:

# Read in 10 vectors into x
x <- lapply(1:10, function(i) scan(paste("myvec",i,".txt", sep=""))
x[[3]] # the vector in myvec3.txt
str(x) # prints an overview of x

c(x1, x2, ... xn)

> x1 <- c(5,7,9)
> 
> x2 <- c(6,3,4)
>
> xn <- c(1,2,3)
> c(x1, x2, xn)
[1] 5 7 9 6 3 4 1 2 3
> 
> matrix(c(x1, x2, xn), ncol=3)
     [,1] [,2] [,3]
[1,]    5    6    1
[2,]    7    3    2
[3,]    9    4    3
> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM