-4

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 Thanks

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

proctor
  • 35
  • 5

2 Answers2

2

Disclaimer: I do not advocate doing what you want to do here. Copying data in this manner is computationally intensive, and likely unnecessary.

Nonetheless, here is how you would go about this. First create an empty data frame of the size that you want.

dims <- dim(df)
ind <- agrep("value",names(df))
new_dims <- c(dims[1], dims[2] +length(ind))
new_df <- data.frame(matrix(rep(NA, prod(new_dims)), nrow = dims[1]))

Then, copy the data to the relevant indices.

names(new_df)[ind + seq_along(ind)] <- "Blue"
new_df[,ind + seq_along(ind)] <- df$Blue
names(new_df)[setdiff(1:new_dims[2], ind + seq_along(ind))] <- names(df)
new_df[,setdiff(1:new_dims[2], ind + seq_along(ind))] <- df

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

You might want to read the first chapter of the R inferno to understand the myriad problems of inefficiently growing objects.

shayaa
  • 2,787
  • 13
  • 19
2

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.

Community
  • 1
  • 1
Frank
  • 66,179
  • 8
  • 96
  • 180