简体   繁体   中英

R: Rename or copy dataframe and naming it as defined in a vector

I want to create a new dataframe from an existing one and naming it as defined in a vector:

I have a dataset with many different questions, and to go through the dataset a bit quicker, I have developed a list of generic functions that can be called upon. For each question, I define the specific values, such as can be seen below. In the second part, I more or less create a clean dataset for the question, which is saved as a dataframe called 'questionid'. Because that variable is overwritten with each question, I want to create a duplicate of this dataframe and call it as specified under 'questionname' (in this case "A1"). I find it very difficult to find easy ways to do that. I hope someone can help me.

# Specify vectors and variables
  question <- "Would you recommend edX to a friend of you?" 
  questionname <- "A1" 
  edXid <- "i4x-DelftX-ET3034TUx-problem-b3d30df864ca41ffa0170e790f01a783_2_1" 
  clevels <- c("0 - Not at all likely", "1", "2", "3", "4", "5 - Neutral", "6", "7", "8", "9", "10 - Extremely likely") 
  csvname <- paste(questionname, ".csv", sep="") 
  pngname <- paste(questionname, ".png", sep="") 

# Run code
  questionid <- subset(allDatasolar, allDatasolar[,3]==edXid, select = -c(X,question))
  questionid <- questionid[-grep("dummy", questionid$answer), ] 
  questionid <- droplevels(questionid) 
  # as.name(questionname) <- as.data.frame(questionid) # does not work
  questionid$answer <- factor(questionid$answer, ordered=TRUE, levels=clevels) 
  write.csv(data.frame(summary(questionid$answer)), file = csvname) 
  png(file = pngname, width = 640) 
  barchart(questionid$answer, main = question, xlab = "", col='lightblue')
  dev.off() 

You're looking for assign


>question = "What do you need?" 
>questionname = "A1" 
>  
>questionid = data.frame(question, x="minimal working example")
>
>assign(questionname, questionid)
>
>A1

           question                       x
1 What do you need? minimal working example

Assign takes a string (or a character variable, in this case) as the first argument and makes an object with that name that is a copy of whatever is in the second argument. In this case, you can feel free to keep over-writing the questionid data frame, but you will be making copies along the way based on your "questionname" variable value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM