开发者

Accessing a vector inside a vector [duplicate]

开发者 https://www.devze.com 2023-04-03 04:36 出处:网络
This question already has answers here: 开发者_如何学Go Closed 11 years ago. Possible Duplicate: Is there a way to access an index within a vector
This question already has answers here: 开发者_如何学Go Closed 11 years ago.

Possible Duplicate:

Is there a way to access an index within a vector

I've posted a similar question recently, however i didn't really receive an answer. I need to access a vector within a list of vectors, this is what the code looks like so far:

MyDataR1 <- scan("D:\\R Code\\Residential\\bvl5 res.txt",what='character') 
MyDataR2 <- scan("D:\\R Code\\Residential\\bvl5 res.txt",what='character') 
MyDataR3 <- scan("D:\\R Code\\Residential\\cpk11 res.txt",what='character')

MyDataR <- c(MyDataR1,MyDataR2,MyDataR3)
print (MyDataR[3])

However the print command doesn't actually print the 3rd vector (MyDataR3), it prints out the 3rd value from the 1st vector (MyDataR1)

Is there any way to access the individual vectors within a vector?? And how would i go about accessing the individual value of a vector within a vector? I thought it would look like this:

MyDataR[[3]][5] <- 5    #this would access the 5th value of the 3rd vector and modifies it

Any help would be greatly appreciated.


The problem is that this line:

MyDataR <- c(MyDataR1,MyDataR2,MyDataR3)

does not do what you think it is doing. It is combining the three arguments into a single vector. Here's a reproducible example of what's going on:

foo <- 1:3
bar <- 4:6
baz <- 7:9

foobarbaz <- c(foo, bar, baz)
> foobarbaz
[1] 1 2 3 4 5 6 7 8 9

What you want to do is create a list object:

mylist <- list(foo, bar, baz)
> mylist[3]
[[1]]
[1] 7 8 9

And can be indexed as you thought:

mylist[[3]][2] <- -1
> mylist[3]
[[1]]
[1]  7 -1  9


c is short for concatenation, so this behavior is obvious. Try using list instead.

0

精彩评论

暂无评论...
验证码 换一张
取 消