我已经阅读了以下答案,但它仅限于解决我现在遇到的问题: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")
答案 0 :(得分: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")