如何在R中的for循环中引用变量名?

如何在R中的for循环中引用变量名?

问题描述:

我正在尝试在R中的for循环中引用变量名.例如,如果我要将以下每个变量从数字更改为字符串

I'm trying to reference variable names in for loop in R. For example, if I want to change each of the following variables to from numeric to a string

xtable<- tbl_df(cbind(x1=c(1,2,3), x2=c(3,4,5)))

for (varname in names(xtable)) {
 xtable$varname<- as.character(xtable$varname)
}

或通过在每个变量名称后添加"a"来重命名每个变量

or rename each variable by adding an 'a' after each variable name

for (varname in names(xtable)) {
 dplyr::rename(xtable, varname = paste0(varname,'a', sep='') )
}

通常,我无法在for循环中将索引变量"varname"作为其表示的变量名称而不是单词"varname"来引用.

In general, I'm having trouble referencing the indexing variable "varname" within the for loop as the variable name it represents rather than as the word "varname".

请注意,dplyr库中描述了tbl_df.但是您可以轻松使用data.frame或as.data.frame.

Note that tbl_df is depricated in the dplyr library. But you can use data.frame or as.data.frame easily.

xtable <- data.frame(x1=c(1,2,3), x2=c(3,4,5))
str(xtable) # shows the structure of the data.frame

R使我们能够轻松地执行矢量运算,从而消除了许多循环的需求.

R allows us to perform vector operations easily which take away the requirements for many loops.

# lapply applies a function to every column in a data.frame
xtable <- as.data.frame(lapply(xtable,as.character))
str(xtable) # shows the structure of the data.frame

# we can directly input into the names() of an object
# paste0 has a default separator of '' 
# If we put a vector into paste0 it will return a vector!
names(xtable) <- paste0(names(xtable),"a")
str(xtable)

但是如果您确实需要在循环中引用变量名(针对另一个问题)

But if you really need to reference a variable name in a loop (for a different problem)

for(varname in names(xtable)) {
  print(xtable[varname]) # xtable[varname] outputs a table with one column including header
  print(xtable[[varname]]) # xtable[[varname]] outputs only the contects of the varname vector
}