简体   繁体   English

R-将数据框中的变量转换为因子

[英]R - Convert variables in data frame to a factor

I have created a data frame from a SQL query using the RODBC package. 我已经使用RODBC包通过SQL查询创建了数据框。 I have a separate single column data frame in which each rows contains a name of a column in the main data set that I would like to convert to a factor. 我有一个单独的单列数据框,其中每行包含要转换为因子的主数据集中一列的名称。

This is the logic though the syntax is obviously wrong. 这是逻辑,尽管语法显然是错误的。

for(c in 1:length(df.ToFactor$IV)-0) {

 VarToFactor<- as.character(df.ToFactor$IV[c])
 df.dataset[VarToFactor]<-factor(df.HRV[VarToFactor])

}

Any help would be appreciated. 任何帮助,将不胜感激。

The subtraction of zero from a vector of integers doesn't make much sense. 从整数向量中减去零没有多大意义。 I suspect you may wnat to use the [[<var-name>]] construction: 我怀疑您可能会使用[[<var-name>]]构造:

for(c in 1:length(df.ToFactor$IV) ) {

 VarToFactor<- as.character(df.ToFactor[["IV"]][c])
 df.dataset[[VarToFactor]]<-factor(df.HRV[[VarToFactor]])
      }

I also changed the "$" operation to the equivalent "[[" operation just because it's safer in programming, although I think in a for-loop at an interactive session it would not cause problems. 我也将“ $”操作更改为等效的“ [[”操作,只是因为它在编程中更安全,尽管我认为在交互式会话的for循环中这不会引起问题。 In addition to the ?Extract page where the detail of "[[" and "[" are described one can find useful information in the "R Inferno" by Patrick Burns. 除了在“提取”页面上描述“ [[”和“ [”的详细信息之外,还可以在Patrick Burns的“ R Inferno”中找到有用的信息。 This particular area is covered on p 52. 在p 52上覆盖了该特定区域。

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

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