2

I would like to use the characters in a vector as the names of character objects aiming to get

first as say "d","e","a","t" etc.

tried this approach but am clearly missing some function to apply to x[i]

x <- c("first","second","third"..)

for (i in 1:length(x)) {
x[i] <- sample(letters,4)
}

TIA

2 Answers 2

2

The function you are looking for is assign():

> x <- c("first","second","third")
> for (i in 1:length(x)) {
+ assign(x[i], sample(letters,4))
+ }
> 
> ls()
[1] "first"  "i"      "second" "third"  "x"     
> first
[1] "t" "d" "u" "j"
> second
[1] "o" "i" "p" "l"
> third
[1] "w" "v" "r" "n"

As an alternative, you could build these vectors as different elements of a list:

> mylist <- list()
> for (i in 1:length(x)) {
+ mylist[[x[i]]] <- sample(letters,4)
+ }
> mylist
$first
[1] "e" "l" "y" "d"

$second
[1] "t" "o" "k" "h"

$third
[1] "g" "x" "p" "b"
Sign up to request clarification or add additional context in comments.

Comments

1

You don't say what you will be doing with this object. You may get the simplest structure by using a named vector:

names(x) <- x
x[] <- sample(letters, 4)

If you do not use the paired bracket on the LHS, the whole vector gets replaced and the names will be lost. You can now access the values with quoted names:

> x
 first second  third fourth 
   "w"    "c"    "r"    "x" 
> x["second"]
second 
   "c" 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.