[R] extract parts of a list before symbol

@vi@e@gross m@iii@g oii gm@ii@com @vi@e@gross m@iii@g oii gm@ii@com
Fri May 26 03:17:37 CEST 2023


Evan,

List names are less easy than data.frame column names so try this:

> test <- list(a=3,b=5,c=11)
> colnames(test)
NULL
> colnames(as.data.frame(test))
[1] "a" "b" "c"

But note an entry with no name has one made up for it.


> test2 <- list(a=3,b=5, 666, c=11)
> colnames(data.frame(test2))
[1] "a"    "b"    "X666" "c"   

But that may be overkill as simply converting to a vector if ALL parts are
of the same type will work too:

> names(as.vector(test))
[1] "a" "b" "c"

To get one at a time:

> names(as.vector(test))[1]
[1] "a"

You can do it even simple by looking at the attributes of your list:

> attributes(test)
$names
[1] "a" "b" "c"

> attributes(test)$names
[1] "a" "b" "c"
> attributes(test)$names[3]
[1] "c"


-----Original Message-----
From: R-help <r-help-bounces using r-project.org> On Behalf Of Evan Cooch
Sent: Thursday, May 25, 2023 1:30 PM
To: r-help using r-project.org
Subject: [R] extract parts of a list before symbol

Suppose I have the following list:

test <- list(a=3,b=5,c=11)

I'm trying to figure out how to extract the characters to the left of 
the equal sign (i.e., I want to extract a list of the variable names, a, 
b and c.

I've tried the permutations I know of involving sub - things like 
sub("\\=.*", "", test), but no matter what I try, sub keeps returning 
(3, 5, 11). In other words, even though I'm trying to extract the 
'stuff' before the = sign, I seem to be successful only at grabbing the 
stuff after the equal sign.

Pointers to the obvious fix? Thanks...

______________________________________________
R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
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