Reputation: 175
I want to duplicate all columns from a big dataframe excepted "names"
example
names affx.998991 affx.998993 affx.999927 ....
an_1_1 A/A T/T C/C A/A
an_1_2 A/A T/T C/C A/A
an_3_1 T/T C/C G/G A/A
and I want something like that
names affx.998991 affx_1.998991 affx.998993 affx_1.998993 affx.999927 affx_1.999927
an_1_1 A/A A/A T/T T/T C/C C/C A/A A/A
an_1_2 A/A A/A T/T T/T C/C C/C A/A A/A
an_3_1 T/T T/T C/C C/C G/G G/G A/A A/A
Thank you for your help
Upvotes: 1
Views: 84
Reputation: 21400
Is this what you're looking for?
Sample data:
df <- data.frame(
affx.998991 = c(1, 2, 3, NA, 4, 5, NA),
affx.998993 = 1:7,
affx.999927 = c(LETTERS[1:7])
)
Stringr
solution:
library(stringr)
df[paste0(str_extract(names(df), "^[a-z]+(?=\\.)"),
".", 1:3, ".",
str_extract(names(df), "(?<=^[a-z]{1,10}\\.)\\d+"))] <- df[,1:3]
If names
always start with string affx.
, this can be simplified thus:
df[paste0("affx.", 1:3, ".", str_extract(names(df), "(?<=affx\\.)\\d+"))] <- df[,1:3]
Base R
solution:
df[paste0("affx.", 1:3, ".", sub("^(affx\\.)(\\d+)$", "\\2", names(df)))] <- df[,1:3]
Result:
df
affx.998991 affx.998993 affx.999927 affx.1.998991 affx.2.998993 affx.3.999927
1 1 1 A 1 1 A
2 2 2 B 2 2 B
3 3 3 C 3 3 C
4 NA 4 D NA 4 D
5 4 5 E 4 5 E
6 5 6 F 5 6 F
7 NA 7 G NA 7 G
Upvotes: 1
Reputation: 456
This should work.
df = data.frame(names = c("an_1_1", "an_1_2"),
affx.998991 = c("A/A", "A/A"),
affx.998993 = c("T/T", "T/T")
)
nc = ncol(df)
vnames = c()
for (i in 2:nc) {
df$dum = df[, i]
names(df)[ncol(df)] = paste("affx_1.",
substr(names(df)[i], 6, nchar(names(df)[i])), sep="")
vnames = c(vnames, c(names(df)[i], names(df)[ncol(df)]))
}
df = df[, c("names", vnames)]
Upvotes: 0
Reputation: 4233
There are two tasks here:
You can do the following (I am using a mock data frame):
df <- data.frame(names = "A", a.b = 1, c.d = 2)
df <- df[ , c(1,rep(2:ncol(df), each=2))]
names(df)[-1][seq(2,ncol(df[-1]),2)] <- gsub("\\.", "\\_", names(df)[-1][seq(1,ncol(df[-1])-1,2)])
which gives
> df
names a.b a_b c.d c_d
1 A 1 1 2 2
starting from
> df
names a.b c.d
1 A 1 2
Upvotes: 1