0

I want to change the name of the data frame using the specific value I get from the data's name. My data comes from the World Bank's Open Data initiative.

My code:

library(readxl)

API_SP_POP_TOTL_DS2_en_excel_v2_3358348 <- read_excel("API_SP.POP.TOTL_DS2_en_excel_v2_3358348.xls", sheet = "Data", skip = 3)

colnames(API_SP_POP_TOTL_DS2_en_excel_v2_3358348) <- sub(" ", "", colnames(API_SP_POP_TOTL_DS2_en_excel_v2_3358348))

indicatorName <- API_SP_POP_TOTL_DS2_en_excel_v2_3358348$IndicatorCode[1]

varName = gsub(".", "", indicatorName, fixed=TRUE)

And then, I want to assign the varName (in this case, varName is SPPOPTOTL) as the name of the Data because it is API_SP_POP_TOTL_DS2_en_excel_v2_3358348, so long.

In short, I want to get this result.

  SPPOPTOTL <- API_SP_POP_TOTL_DS2_en_excel_v2_3358348

I do not want to type in the varName, SPPOPTOTL, directly.

1
  • Not recommended in general, but have a look at assign. Commented Dec 3, 2021 at 6:05

1 Answer 1

2

Here is one option for getting the variable name, then as @user2974951 suggested, you can use assign. This will create SPPOPTOTL and add it to the global environment.

library(tidyverse)

varName <- API_SP_POP_TOTL_DS2_en_excel_v2_3358348 %>%
  dplyr::pull("Indicator Code") %>%
  head(1) %>%
  str_replace_all(., "[[:punct:]]", "")

assign(x = varName, value = API_SP_POP_TOTL_DS2_en_excel_v2_3358348)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.