[R] working on a vector with named elements - unname
Petr PIKAL
petr.pikal at precheza.cz
Wed Feb 15 16:45:41 CET 2012
Hi
> Hi, I am working under R2.11.1 Windows.
Rather old one, consider upgrading
> I work with a set of parameters which is save under a vector. I think it
is
> easier to understand, which parameter is called in the vector by naming
all
> vector elements. For example, we have a vector which the parameters
a,b,c,d.
> Is it normal to allow, that there are two elements with the same name? I
> think for lists, it is also possible. If I want to regroup the elements
and
> work on them, they always keep their old name. Event if I attribute to a
new
> name, the new name and the old name merge (lign3)
>
> v<-c("a"=3,"a"=4,"c"=5,"d"=6)
> v["a"] #output 3
> c("n"=v["a"]+v["c"],"n1"=v["d"]*3) # "n.a"=8 "n1.d"=18
>
> Is there any better solution/datatype to this ?
I am not at all an expert in such things but named vector seems to me
rather strange solution.
compare
v<-c("a"=3,"a"=4,"c"=5,"d"=6)
vl<-list("a"=c(3,4),"c"=5,"d"=6)
> v["a"]
a
3
> vl["a"]
$a
[1] 3 4
> vl[["a"]]
[1] 3 4
>
This seems to me not correct
> c("n"=v["a"]+v["c"])
n.a
8
as there are two values named "a", why only first shall be used?
while this seems to me correct
> c("n"=vl[["a"]]+vl[["c"]])
n1 n2
8 9
both "a" values are included in computation
>
> c("n"=unname(v["a"])+unname(v["c"]),"n1"=unname(v["d"])*3) # "n"=8
"n1"=18
Instead of
c("n"=unname(v["a"])+unname(v["c"]),"n1"=unname(v["d"])*3)
n n1
8 18
or
c("n"=vl[["a"]]+vl[["c"]],"n1"=vl[["d"]]*3)
n1 n2 n1
8 9 18
I would use list which again seems to get more reasonable result.
list("n"=vl[["a"]]+vl[["c"]],"n1"=vl[["d"]]*3)
$n
[1] 8 9
$n1
[1] 18
Lists are not as complicated as they seems to be when you start with them.
You can imagine them as a chest of drawers and you can store any kind of
information in it. You can easily access only one ore some set of drawers.
Regards
Petr
>
> Thanks a lot
>
>
> --
> View this message in context:
http://r.789695.n4.nabble.com/working-on-a-
> vector-with-named-elements-unname-tp4389930p4389930.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
More information about the R-help
mailing list