【问题标题】:How to name only particular rows in a df in R?如何仅命名R中df中的特定行?
【发布时间】:2018-09-29 16:13:55
【问题描述】:

我最近尝试仅命名数据框中的部分行,但不知道如何操作。我认为 df 的“row.names”可能会有所帮助,但看起来我无法命名某些行,我必须命名所有行才能使其正常工作。 至少这段代码没有改变任何行名:

example_df <- data.frame(rnorm(5), rnorm(5), rnorm(5))
row.names(example_df[c(1,2),]) <- c('11', '12')
row.names(example_df[3,]) <- 'a'

那么我怎样才能只更改部分行名呢?

【问题讨论】:

    标签: r dataframe rowname


    【解决方案1】:

    这会起作用 -

    example_df <- data.frame(rnorm(5), rnorm(5), rnorm(5))
    row.names(example_df)[1:2] <- c('11', '12')
    row.names(example_df)[3] <- 'a'
    
    #    rnorm.5. rnorm.5..1  rnorm.5..2
    # 11 -0.5374545 -1.0895643 -0.09938087
    # 12 -0.6822140 -0.2806339  1.38078815
    # a  -0.8664183 -0.5729183 -0.84851810
    # 4  -0.9269735  0.4403557 -0.05622809
    # 5   2.1156331 -1.1441339 -1.04363951
    

    【讨论】:

    • 谢谢,成功了!你知道为什么这段代码有效而另一个无效吗?在我看来 row.names(example_df[3,]row.names(example_df)[3] 是一回事,但显然不是。
    • 我在这里只是胡乱猜测 - 也许使用 example_df[3, ] 参数为 row.names 实际上并没有将它指向全局环境中的 example_df 对象。您应该将此作为单独的问题提出,以便更有经验的程序员可以为您提供正确的答案。
    猜你喜欢
    • 1970-01-01
    • 2022-07-19
    • 2022-07-28
    • 2017-08-23
    • 1970-01-01
    • 1970-01-01
    • 2020-09-20
    • 2015-05-02
    • 1970-01-01
    相关资源
    最近更新 更多