【问题标题】:R: changing all string nominal columns to integersR:将所有字符串名义列更改为整数
【发布时间】:2015-12-11 07:50:28
【问题描述】:

我有一个数据集,我打算在其中使用不平衡包的 ubRacing。但是这个 ubRacing 只接受数字列。无论如何我可以通过 R 将所有 chr 列转换为数字吗?

谢谢

'data.frame':31000 obs。 22 个变量:

$ ID            : int  1 2 3 4 5 6 7 8 9 10 ...
 $ age           : int  56 57 37 40 56 45 59 41 24 25 ...
 $ job           : chr  "housemaid" "services" "services" "admin." ...
 $ marital       : chr  "married" "married" "married" "married" ...
 $ education     : chr  "basic.4y" "high.school" "high.school" "basic.6y" ...
 $ default       : chr  "no" "unknown" "no" "no" ...
 $ housing       : chr  "no" "no" "yes" "no" ...
 $ loan          : chr  "no" "no" "no" "no" ...
 $ contact       : chr  "telephone" "telephone" "telephone" "telephone" ...
 $ month         : chr  "may" "may" "may" "may" ...
 $ day_of_week   : chr  "mon" "mon" "mon" "mon" ...

【问题讨论】:

  • 根据您的示例,这将导致这些列中的所有 NA 值
  • 您想如何将具有housemaidservices 等的job 列转换为numeric
  • 对不起!直到现在我还没有看到。是我的室友通过登录我的笔记本电脑发表了评论并接受了。是的,您的回答很有帮助。谢谢。

标签: r


【解决方案1】:

不清楚如何将character 列转换为numeric。一种可能的选择是将character 类转换为factor,然后将其强制转换为numeric。我们使用lapply 遍历数据集的列。

df1[] <- lapply(df1, function(x) if(is.character(x)) as.numeric(factor(x))
                                     else (x))

【讨论】:

    猜你喜欢
    • 2015-10-24
    • 1970-01-01
    • 2015-08-02
    • 2020-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-15
    • 2023-03-20
    相关资源
    最近更新 更多