Froom2
Froom2

Reputation: 1279

Specifying column names in functions

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")

Upvotes: 0

Views: 114

Answers (1)

Michele
Michele

Reputation: 8753

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")

Upvotes: 2

Related Questions