【问题标题】:how to delete the first n characters of rownames in a data frame? R如何删除数据框中行名的前 n 个字符? R
【发布时间】:2016-01-09 03:47:29
【问题描述】:

我有一个如下所示的数据框:

                    date_tmp  efficiency        smb      rmrf      hml   rmw      cma    Returns
2010-11-04.Stock1 2010-11-04  0.4469618 0.87430339 0.7337814 0.00000000   0 0.60769928 1.245834
2010-11-04.Stock2 2010-11-04  0.6608003 0.65057967 2.2088113 0.00000000   0 0.10672836 1.659817
2010-11-04.Stock3 2010-11-04  0.3878181 0.88259984 0.2530008 0.04665325   0 1.38739047 1.388948
2010-11-04.Stock4 2010-11-04  0.4781154 0.93226537 0.0000000 0.16319179   0 1.43025290 1.331511
2010-11-04.Stock5 2010-11-04  0.4809276 0.56507215 1.9185010 0.00000000   0 0.09270075 1.441663
2010-11-04.Stock6 2010-11-04  0.4619094 0.06452728 1.8513120 0.00000000   0 0.40841138 1.251019

第一列显示行名。

我需要的是删除所有行上的日期部分,例如(“Stock1”而不是“2010-11-04.Stock1”

我基本上需要这个函数的反转,它保留前 n 个字符而不是删除它们。

x <- "some text in a string"

substrRight <- function(x, n){
  substr(x, 1, n)
}

substrRight(x, 4)
[1] "some"

【问题讨论】:

  • rownames(data) &lt;- sub(".*\\.", "", rownames(data)) 可能会这样做
  • 理查德所说的。而你写的函数的反面是substr(x, nchar(x)-n+1, nchar(x))
  • 因为您询问了substrsubstr(rownames(df1), nchar(rownames(df1))-5, nchar(rownames(df1))) 但我会使用@RichardScriven 评论的sub,因为当数字> 9 时,字符数是可变的。
  • 工作得很好,谢谢!

标签: r rowname


【解决方案1】:

例如,如果日期部分是您要删除的部分,您可能需要考虑使用正则表达式

foo = function(x){
    return(gsub(".+\\.","",x))
}

如果您执行 foo("2010-11-04.Stock1") 将返回“Stock1”

【讨论】:

    猜你喜欢
    • 2019-04-25
    • 2016-03-06
    • 1970-01-01
    • 1970-01-01
    • 2016-06-11
    • 2021-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多