proctor proctor - 1 year ago 72
R Question

Inserting a column after a specific column

How do I add a column of data, e.g named "Blue" after every column that contains the word "value"? I prefer to use data.table but cannot find a solution

Blue BCS_code1 BCS_code2 BCS_value Wt_code1 Wt_code2 Wt_value
1/05 125 255 4 258 154 6
6/06 256 525 8 112 254 6

And I need

Blue BCS_code1 BCS_code2 BCS_value Blue Wt_code1 Wt_code2 Wt_value Blue
1/05 125 255 4 1/05 258 154 6 1/05
6/06 256 525 8 6/06 112 254 6 6/06

I realise there will be mutiple columns named "Blue" but that is fine for what I need

Answer Source

Similar to @shayaa's answer, and following the strategy in Wojciech Sobala's answer elsewhere:

w0       = which(names(DT) %like% "value")
w        = w0 + seq_along(w0)

cols     = character(length(DT) + length(w))
cols[w]  = "Blue"
cols[-w] = names(DT)

DT[, cols, with=FALSE]

Without data.table, use which(grepl("value", names(DT))) in the first line and DT[cols] for the last.

The code above isn't adding columns to the original table, as the OP was interested in. Doing so with repeated names is very messy for a data.table, presumably by design, since it is a bad idea.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download