Ashag
Ashag

Reputation: 867

Generate column names dynamically for a dataframe in R

So, I am coverting a json into dataframe using and I'm successful in doing that. Below is my code:

df <- data.frame(t(sapply(json, c)))
colnames(df) <- gsub("X", "y",colnames(df))

So, it gives me column names like y1,y2,y3 etc. Is it possible if I could have these column names generated from 0 instead. So, the column names should be like y0,y1,y2 etc.

Upvotes: 1

Views: 2599

Answers (1)

Geochem B
Geochem B

Reputation: 418

From the comments:

df <- data.frame(t(sapply(json,c))
colnames(df) <- paste0("y", 0:(ncol(df)-1))

Or if you want padded zeros

a <- seq(0,ncol(df)-1,1)
colnames(df) <- sprintf("y%02d",a)

Upvotes: 4

Related Questions