Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

r - how to use a variable in a variable

I have a data frame where the row names are words and I can call the first column of that row of data drame using something like

>df['rowB',1]

i know I can use paste to combine a variable and a string using paste to do something like

>paste("the value is ", df['rowB',1], "."]

and that will get me an output of the string with the value of the variable. what if rowname is a variable that equals 'rowB? I tried to do a first paste to put in the paste above, but the result of the first paste doesn't evaulate to the value, but rather is just a string that says

>rowname<-'rowB'
>type<-paste("relatype['", rowname, "',1]", sep="")
'df['rowB',1]'

long story short, I want to input a value called 'rowname' as a parameter of a function and have it be evaluated for the value of rowname, so I can then put that value into a string within that same function.

I'm also open to a wholly different solution. any and all suggestions are welcome.

thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This should work:

paste("the value is ", get(df['rowname',1]), "."]

If you are not familiar, 'get' in r is similar to 'eval' in python.

x=c('a', 'c', 'b')
a=2
x[1]
'a'
get(x[1])
2

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...