Code to rename multiple columns in rStudio

I want to rename this columns in R, I want to remove X from each of them so that it remains just figures which represents different years varying from 1960 to 2020. The first two (country name and Country Code) are sorted out already.

[1] "ï..Country.Name" "Country.Code"    "X1960"           "X1961"           "X1962"          
 [6] "X1963"           "X1964"           "X1965"           "X1966"           "X1967"          
[11] "X1968"           "X1969"           "X1970"           "X1971"           "X1972"          
[16] "X1973"           "X1974"           "X1975"           "X1976"           "X1977"          
[21] "X1978"           "X1979"           "X1980"           "X1981"           "X1982"          
[26] "X1983"           "X1984"           "X1985"           "X1986"           "X1987"          
[31] "X1988"           "X1989"           "X1990"           "X1991"           "X1992"          
[36] "X1993"           "X1994"           "X1995"           "X1996"           "X1997"          
[41] "X1998"           "X1999"           "X2000"           "X2001"           "X2002"          
[46] "X2003"           "X2004"           "X2005"           "X2006"           "X2007"          
[51] "X2008"           "X2009"           "X2010"           "X2011"           "X2012"          
[56] "X2013"           "X2014"           "X2015"           "X2016"           "X2017"          
[61] "X2018"           "X2019"           "X2020" 

Upvotes: 0

Views: 63

Answers (1)

user2332849
user2332849

Reputation: 1450

names(df) <- gsub("^X", "", names(df))

gsub() matches a regular expression and replaces it if found. In our case, the regex says the string must have an X at the beginning.

Upvotes: 1

Related Questions