简体   繁体   English

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

[英]How to reference variable names in a for loop in R?

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 我正在尝试在R中的for循环中引用变量名。例如,如果要将以下每个变量都从数字更改为字符串

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)
}

or rename each variable by adding an 'a' after each variable name 或通过在每个变量名称后添加“ a”来重命名每个变量

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

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". 通常,在将for循环中的索引变量“ varname”作为其表示的变量名称而不是单词“ varname”引用时遇到麻烦。

As others have mentioned, there is no need to use a for loop in both of your cases. 正如其他人提到的,在两种情况下都不需要使用for循环。 There are two convenience functions in dplyr called mutate_all and mutate_if that will let you do the first case very easily: dplyr有两个便捷函数, dplyr称为mutate_allmutate_if ,它们使您可以很轻松地完成第一种情况:

library(dplyr)

# Convert all columns to character
xtable %>%
  mutate_all(as.character)

# Convert all numeric columns to character
xtable %>%
  mutate_if(is.numeric, as.character)

Result: 结果:

# A tibble: 3 x 2
     x1    x2
  <chr> <chr>
1     1     3
2     2     4
3     3     5

For second case, you can also use setNames and chain it with the first case: 对于第二种情况,您还可以使用setNames并将其与第一种情况链接起来:

xtable %>%
  mutate_all(as.character) %>%
  setNames(paste0(names(xtable), "a"))

Result: 结果:

# A tibble: 3 x 2
    x1a   x2a
  <chr> <chr>
1     1     3
2     2     4
3     3     5

Note that tbl_df is depricated in the dplyr library. 请注意,dblyr库中描述了tbl_df。 But you can use data.frame or as.data.frame easily. 但是您可以轻松使用data.frame或as.data.frame。

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

R allows us to perform vector operations easily which take away the requirements for many loops. R使我们能够轻松执行矢量运算,从而消除了许多循环的要求。

# 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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM