在特定列之后插入列

时间:2016-08-11 02:29:35

标签: r data.table

如何在包含单词“value”的每列之后添加一列数据,例如名为“Blue”?我更喜欢使用data.table但无法找到解决方案 感谢

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

我需要

 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

我意识到会有多个名为“Blue”的列,但这对我需要的内容很好

2 个答案:

答案 0 :(得分:2)

免责声明:我不主张做你想做的事。以这种方式复制数据是计算密集型的,并且可能是不必要的。

尽管如此,以下是你如何做到这一点。首先创建一个所需大小的空数据框。

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]))

然后,将数据复制到相关索引。

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

您可能希望阅读R inferno的第一章,以了解无效增长对象的无数问题。

答案 1 :(得分:2)

与@ shayaa的答案类似,并遵循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]

如果没有data.table,请在第一行使用which(grepl("value", names(DT))),在最后一行使用DT[cols]

上面的代码并没有像OP那样在原始表中添加列。对于data.table来说,重复名称这样做非常混乱,大概是设计,因为这是一个坏主意。