addressalign-toparrow-leftarrow-rightbackbellblockcalendarcameraccwcheckchevron-downchevron-leftchevron-rightchevron-small-downchevron-small-leftchevron-small-rightchevron-small-upchevron-upcircle-with-checkcircle-with-crosscircle-with-pluscrossdots-three-verticaleditemptyheartexporteye-with-lineeyefacebookfolderfullheartglobegmailgooglegroupshelp-with-circleimageimagesinstagramlinklocation-pinm-swarmSearchmailmessagesminusmoremuplabelShape 3 + Rectangle 1ShapeoutlookpersonJoin Group on CardStartprice-ribbonShapeShapeShapeShapeImported LayersImported LayersImported Layersshieldstartickettrashtriangle-downtriangle-uptwitteruserwarningyahoo

Bay Area useR Group (R Programming Language) Message Board Bay Area useR Group (R Programming Language) Discussion Forum › Naming an Object From a Character Vector

Naming an Object From a Character Vector

Brad B.
user 14534071
Broken Arrow, OK
Post #: 2
Hello. I am not a software developer, just an engineer who sits at a computer all day and occasionally writes scripts.

I am using R to study statistics in a class offered at work. I am also using R for a software tool I am making. The short script that follows is a simple way of describing a problem I have. If any of you can tell me how to do it, I will appreciate it greatly.

Brad

# This is a test script to learn how to
# name objects from characters in a vector
objnm <- character(length = 4)
objnm[1]="dog"
objnm[2]="rat"
objnm[1]
objnm
dog
rat
# I want to determine the contents of objnm[1]
# and use that as a name for an object.
# Then I want to set dog = 2.
# When I type dog, as shown next, I want dog to = 2.
dog

Robert M. Horton, ...
user 12069592
San Francisco, CA
Post #: 2
objnm <- c("dog", "rat", NA, NA)
assign(objnm[1], 2)
dog
Brad B.
user 14534071
Broken Arrow, OK
Post #: 3
Dr. Horton - Thank you very much.... and I mean it.
Robert M. Horton, ...
user 12069592
San Francisco, CA
Post #: 3
Sure, this is fun. If you're keeping track of things by name, you might want to look into named lists. Try this:


zoodata <- list(dog=2, cat=1, cow=9)
zoodata['dog'] # returns a sublist of one
zoodata[['dog']] # returns a single item

which(zoodata==1) # get the index of the matching item
names(zoodata)[which(zoodata==1)] # get the name of the matching item
zoodata[[names(zoodata)[which(zoodata=­=1)]]] # round trip

Brad B.
user 14534071
Broken Arrow, OK
Post #: 5
I'll keep the named lists in mind. In a week or two I'll have to clean up my code and implement better ways of doing things. Thanks again!
Powered by mvnForum

Our Sponsors

People in this
Meetup are also in:

Sign up

Meetup members, Log in

By clicking "Sign up" or "Sign up using Facebook", you confirm that you accept our Terms of Service & Privacy Policy