r-如何在变量中使用变量 [英] 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]
我知道我可以使用粘贴
>paste("the value is ", df['rowB',1], "."]
,这将使我得到带有如果rowname是一个等于'rowB?的变量,该怎么办?我试图在上面的粘贴中添加第一个粘贴,但是第一个粘贴的结果并没有移到该值上,而是一个
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]'
长话短说,我想输入一个名为行名的值作为函数的参数,并对其进行计算以获取rown的值ame,因此我可以将该值放入同一函数中的字符串中。
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.
谢谢
推荐答案
不确定问题可能是什么,从您的描述中还不能完全清楚,但是如果行名是一个变量,则不需要任何特殊的东西,因为无论如何它都会求值。让
Not sure what the problem might be, not entirely clear from your description, but if rowname is a variable, you don't need anything special, because it will evaluate to it's value anyway. Let
mat <- matrix(1:10, nrow = 5)
rownames(mat) <- letters[1:5]
mat
## [,1] [,2]
##a 1 6
##b 2 7
##c 3 8
##d 4 9
##e 5 10
rowname<- b
,然后
rowname
##[1] "b"
所以
mat[rowname, 1]
##b
##2
与 mat [ b,1]
相同。如果您使用 mat ['rowname',1]
,它只会失败。
如果要将其放入函数中,则可以执行以下操作:
which is the same as mat["b", 1]
. It only fails, if you use mat['rowname', 1]
.
If you want to put this in functions, you can do something like:
getElement <- function(mat, row.name, column.index) {
mat[row.name, column.index]
}
getElement(mat, "b", 1)
##b
##2
pasteSenstence <- function(mat, row.name, col.index) {
paste("The element of row", row.name, "and column", col.index, "is",
getElement(mat, row.name, col.index))
}
pasteSentence(mat, "b", 1)
##[1] "The element of row b and column 1 is 2"
也可以与 rowname<- b
pasteSentence(mat, rowname, 1)
##[1] "The element of row b and column 1 is 2"
这篇关于r-如何在变量中使用变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!