【问题标题】:Remove the "X" letter from the column names of a new dataframe [duplicate]从新数据框的列名中删除“X”字母[重复]
【发布时间】:2019-05-29 09:05:32
【问题描述】:

我正在尝试按year 分组并对每个year 求和weight,但是当我创建新数据框时,列名以“X2000”之类的烦人“X”开头,而不是@ 987654326@。当然,我可以在创建后删除它或将其替换为“”,但我不希望从一开始就创建它,因为此方法将应用于具有更多列的数据帧。

library(tidyverse)

year<-c("2000","2000","2001","2002","2000","2002")
weight<-c(0.5,0.7,0.8,0.7,0.6,0.9)
YG<-data.frame(year,weight)


w<-data.frame(YG %>%
                     group_by(year) %>%
                     summarise(n = round(sum(weight)),
                               g = n()) %>%
                     select(-g) %>%
                     spread(year, n, fill = 0))

【问题讨论】:

  • 问题是您试图用数字名称替换 colnames。也许将 colnames 设置为非数字的东西?
  • 为什么需要用data.frame包裹。 tibble 输出很好
  • 欲了解更多信息,请查看here
  • 我稍后会更容易操作,但我理解你的问题

标签: r


【解决方案1】:

虽然不是真正可取的,但您想要的是 check.names = FALSEdata.frame 调用中:

data.frame(YG %>% group_by(year) %>%
             summarise(n = round(sum(weight)), g = n()) %>%
             select(-g) %>% spread(year, n, fill = 0), 
           check.names = FALSE)
#   2000 2001 2002
# 1    2    1    2

【讨论】:

  • 很高兴知道有这个选项。使用as.data.frame(无选项)也可以
【解决方案2】:

另一种选择:new_YG 是 w

names(new_YG)<-sapply(str_remove_all(colnames(new_YG),"X"),"[")
names(new_YG)
new_YG

【讨论】:

    猜你喜欢
    • 2019-02-28
    • 2018-04-29
    • 1970-01-01
    • 2012-07-18
    • 1970-01-01
    • 2012-11-13
    • 2017-11-25
    • 2017-08-03
    • 1970-01-01
    相关资源
    最近更新 更多