I have some data that looks like this:
country agdp apop
1 US 100 100
2 Australia 50 50
Run Code Online (Sandbox Code Playgroud)
The variable names are agdp and apop, but I would like them to be gdp and pop. My real data has many, many variables that all need that transformation.
And this is what my desired outcome:
country gdp pop
1 US 100 100
2 Australia 50 50
Run Code Online (Sandbox Code Playgroud)
Reproducible code below:
df <- data.frame(stringsAsFactors=FALSE,
country = c("US", "Australia"),
agdp = c(100, 50),
apop = c(100, 50)
desired_df <- data.frame(stringsAsFactors=FALSE,
country = c("US", "Australia"),
gdp = c(100, 50),
pop = c(100, 50)
Run Code Online (Sandbox Code Playgroud)
一种dplyr可能性可能是:
df %>%
rename_at(2:length(.), list(~ substr(., 2, nchar(.))))
country gdp pop
1 US 100 100
2 Australia 50 50
Run Code Online (Sandbox Code Playgroud)
与以下相同base R:
names(df)[-1] <- substr(names(df)[-1], 2, nchar(names(df)[-1]))
Run Code Online (Sandbox Code Playgroud)