Reputation: 437
Can I generate the variable name in R by combine a character and a value from a column of dataset dynamically and store the new variable to a vector. For example, we have the dataset as
col1 col2
8 4
3 6
4 3
5 5
I hope the col1 can be a part of the new variable name and col2 be the value of the new variable. For example, I hope I can get the following result,
x8 = 4, x3 = 6, x4 = 3, x5 = 5
where the number 8,3,4,5 in the part of variable name is from col1 and "x" is the character I can choose. And I also hope I can store the variable name to a vector automatically. Thanks.
Upvotes: 0
Views: 72
Reputation: 94162
Don't go around creating variable names automatically. Its a bad thing. If your data items are related, you want to store them in a single object. You might be happier in the long term with a list. For example, starting with df
:
n=list()
n[paste0("x",df$col1)]=df$col2
Now you can get a value via n$x3
:
> n$x3
[1] 6
The entries in the list can be got with names
:
> names(n)
[1] "x8" "x3" "x4" "x5"
The bonus here is that you haven't cluttered up your space with lots of variables and you dont have to separately handle a list of the names of the things you created. If you want to do something over all those values you just loop over the entries in the list. eg, which ones are over 4?
> for(nm in names(n)){if(n[nm]>4){print(nm)}}
[1] "x3"
[1] "x5"
There are better ways of doing that exact thing, but this should get you started.
Upvotes: 2
Reputation: 6659
Not too clear what you are looking for... but here's a shot
df <- read.table(textConnection("col1 col2
8 4
3 6
4 3
5 5"), header=T)
> df
col1 col2
1 8 4
2 3 6
3 4 3
4 5 5
> paste0("x", df$col1)
[1] "x8" "x3" "x4" "x5"
a <- df$col2
names(a) <- paste0("x", df$col1)
> a
x8 x3 x4 x5
4 6 3 5
Upvotes: 0