hjw hjw - 24 days ago 4x
R Question

zoo create new column with dynamic column name

I am trying to add a column to a zoo object. I found merge which works well

test = zoo(data.frame('x' = c(1,2,3)))
test = merge(test, 'x1' = 0)

However when I try to name the column dynamically, it no longer works

test = merge(test, paste0('x',1) = 0)
Error: unexpected '=' in "merge(test,paste0('x',1) ="

I have been working with data frames and the same syntax works

test = data.frame('x' = c(1,2,3))
test[paste0('x',1)] = 0

Can someone help explain what the problem is and how to get around this?


Try setNames :

setNames( merge(test, 0), c(names(test), paste0("x", 1)) )

or names<-.zoo like this:

test2 <- merge(test, 0)
names(test2) <- c(names(test), paste0("x", 1))