Remove the "X" letter from the column names of a new dataframe

Viewed 3126

I am trying to group by year and sum the weight for each year but when my new data frame is created the column names begin with an annoying "X" like "X2000" instead of 2000. Of course I could just delete it or replace it with "" after creation but I want it not be created from the very beginning since this method will be applied to dataframes with more columns.

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))
2 Answers

While not really advisable, what you want is check.names = FALSE in the data.frame call:

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

An alternative: new_YG is w

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