r - How to create new columns in data.frame on the fly? -
similar question
basically want create new column in data.frame on go. might bad practice, i'm doing solution.
right i've tried :
test <- iris create.new_var <- function(x) { assign(paste("test$", x, sep=""), test$petal.width) return(test) } test <- create.new.var('cheese')
the function runs without breaking. data.frame test not contain new column heading 'cheese' , values of iris$petal.width 1 imagine should.
using assign
kind of operations not recommended. but, if need try assign
, possible option is
create.new_var <- function(x){ assign('test', `[[<-`(test, x, value=test$petal.width), envir=.globalenv) } test <- create.new_var('cheese') head(test,3) # sepal.length sepal.width petal.length petal.width species cheese #1 5.1 3.5 1.4 0.2 setosa 0.2 #2 4.9 3.0 1.4 0.2 setosa 0.2 #3 4.7 3.2 1.3 0.2 setosa 0.2
you can add data , replacement column argument in function
create.new_var <- function(dat, x, x1){ str1 <- deparse(substitute(dat)) assign(str1, `[[<-`(dat, x, value=dat[,x1]), envir=.globalenv) } test <- create.new_var(test, 'cheese', 'petal.width')
here option without using assign
, or paste
(some deleted posts used similar method).
create.new_var2 <- function(dat, x, x1){ dat[,x] <- dat[,x1] dat} create.new_var2(test, 'cheese', 'petal.width')
Comments
Post a Comment