给出以下数据框:
> header = c("A1","A2","A3","B1","B2","B3")
> df = matrix(c(0,0,0,0,0,0),nrow = 1)
> colnames(df) = header
> df
A1 A2 A3 B1 B2 B3
[1,] 0 0 0 0 0 0
我知道包含“2”的标题的列索引编号:
> index2 = grep("2", colnames(df))
> index2
[1] 2 5
我想在索引为2和5的列旁边添加两个名为“A2.1”,“A2.2”和“B2.1”,“B2.2”的列,以便:
A1 A2 A2.1 A2.2 A3 B1 B2 B2.1 B2.2 B3
[1,] 0 0 0 0 0 0 0 0 0 0 0
我可以这样做吗?
非常感谢提前!
答案 0 :(得分:4)
假设您要根据'index2'插入列,一个选项是
df1 <- cbind(df, do.call(cbind,
replicate(2,df[,index2, drop=FALSE], simplify=FALSE)))
df2 <- df1[,order(colnames(df1)), drop=FALSE]
colnames(df2) <- make.unique(colnames(df2))
df2
# A1 A2 A2.1 A2.2 A3 B1 B2 B2.1 B2.2 B3
#[1,] 0 0 0 0 0 0 0 0 0 0
答案 1 :(得分:3)
您可以尝试这样的事情:
set.seed(1234)
df <- data.frame(matrix(runif(100),ncol=5))
colnames(df) <- LETTERS[1:ncol(df)]
B.1 <- runif(20)
df <- cbind(df,B.1)
df <- df[,order(colnames(df))]
#> head(df)
# A B B.1 C D E
#1 0.1137034 0.31661245 0.03545673 0.5533336 0.86483383 0.9264005
#2 0.6222994 0.30269337 0.56507611 0.6464061 0.04185728 0.4719097
#3 0.6092747 0.15904600 0.28025778 0.3118243 0.31718216 0.1426153
#4 0.6233794 0.03999592 0.20419632 0.6218192 0.01374994 0.5442698
#5 0.8609154 0.21879954 0.13373890 0.3297702 0.23902573 0.1961747
#6 0.6403106 0.81059855 0.32568192 0.5019975 0.70649462 0.8985805
这意味着您首先使用cbind()
附加右侧的列,然后对列序列进行排序。希望这会有所帮助。