【问题标题】:R name column when creating data frame创建数据框时的R名称列
【发布时间】:2012-01-10 01:09:31
【问题描述】:

我正在从数据框中获取列并使用它们来创建另一个数据框,但名称不断变得混乱,而不是保留原始名称。我该如何避免这种情况?

> newDigit1 <- data.frame((security_id = rsPred1$security_id))
> head(newDigit1)
  X.security_id...rsPred1.security_id.
1                                    1
2                                    6
3                                    5
4                                    3
5                                    3
6                                    2

应该是这样的:

> newDigit1 <- data.frame((security_id = rsPred1$security_id))
> head(newDigit1)
                                security_id
1                                    1
2                                    6
3                                    5
4                                    3
5                                    3
6                                    2

【问题讨论】:

    标签: r dataframe creation


    【解决方案1】:

    这是因为你把括号 (( 加倍了。 比较

    dfr <- data.frame(x = 1:5)
    #Case 1
    data.frame(x = dfr$x)
    #Case 2
    data.frame((x = dfr$x))
    

    在情况 1 中,x = dfr$x 是传递给 data.frame 函数的名称-值对。

    在情况 2 中,(x = dfr$x) 返回一个没有名称的向量,因此 R 发明了一个临时向量,然后将该向量传递给 data.frame 函数。

    【讨论】:

    • 谢谢,不错,成功了。
    【解决方案2】:

    创建数据框时,不要使用双括号:

    newDigit1 <- data.frame(security_id = rsPred1$security_id)
    

    不是

    newDigit1 <- data.frame((security_id = rsPred1$security_id))
    

    【讨论】:

      【解决方案3】:

      只需删除一个括号:

      newDigit1 <- data.frame(security_id = rsPred1$security_id)
      

      现在应该可以工作了!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-01-10
        • 2015-02-25
        • 1970-01-01
        • 1970-01-01
        • 2020-09-29
        • 1970-01-01
        • 2016-07-10
        相关资源
        最近更新 更多