0

I have read the following answer, but it stops just short of covering what I am now having trouble with: Pass a data.frame column name to a function

I want to select columns and assign values to a new column based on what's in the old column.

Example:

test <- data.frame(A = c(1:10),
               B = c(1:10), C = c(1:10),
               P = c(1:10))

This works:

change <- function(data){
  if("P" %in% colnames(data)) {        
    data$Z <- NA
    data$Z[data$P==1] = 99
    data$P <- NULL
  }
  return(data)
}
test2 <- change(test)

But I would like to specify the new and old columns in the arguments of the function.

I then tried this, but it doesn't work:

change <- function(data, oldcol, newcol){
  if(oldcol %in% colnames(data)) {        
    data[newcol] <- NA
    data[newcol][data[oldcol==1]] = 99  # I think it's this line I've got wrong
    data[oldcol] <- NULL
  }
  return(data)
}
test2 <- change(test, "P", "Z")

1 Answer 1

2
change <- function(data, oldcol, newcol){
  if(oldcol %in% colnames(data)) {        
    data[newcol] <- NA
    data[newcol][data[oldcol]==1] <- 99  # I think it's this line I've got wrong
    data[oldcol] <- NULL
  }
  return(data)
}
test2 <- change(test, "P", "Z")
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.