0

我已经阅读了以下答案,但它没有涵盖我现在遇到的问题: Pass a data.frame column name to a function

我想根据旧列中的内容选择列并为新列分配值。

例子:

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

这有效:

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)

但我想在函数的参数中指定新旧列。

然后我尝试了这个,但它不起作用:

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

1 回答 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")
于 2013-06-27T11:32:52.477 回答