Analyst_21
Analyst_21

Reputation: 13

Removing first letter of my columns starting from 2nd columns R

I am working on the World Bank datasetbase with R.

My dataset looks like this:

name code y1 y2 y3 y4 .... y2000
Dan  D1   0  1 2 0 .... 2
Max  M1   0  2 0 4 .... 6

I want to remove the "y" at the beginning of every column name, starting from the 3rd column.

name code 1 2 3 4 .... 2000
Dan D1  0 1 2 0 .... 2
Max M1  0 2 0 4 .... 6

I tried:

names(dataset_1[,c(3:2002)])<-substring(names(dataset_1[,c(3:2002)]), 2)

But it doesn't work..

Upvotes: 1

Views: 43

Answers (1)

gfgm
gfgm

Reputation: 3647

You can do this, although R does not like column names to be numbers, so if you can avoid it I would:

df <- data.frame(a = 1, b = 2, y1 = 1, y2 = 1, y3 = 1)
df
#>   a b y1 y2 y3
#> 1 1 2  1  1  1

names(df)[3:ncol(df)] <- substring(names(df)[3:ncol(df)], 2)
df
#>   a b 1 2 3
#> 1 1 2 1 1 1

To access a column, you will need to write df$'1' rather than simply df$1

Upvotes: 1

Related Questions