我有一个名为mydf
的数据框。我想以这样的方式扩展这个数据框,即我得到由"分隔的所有列值的样本的成对组合:"得到如下所示的结果:
mydf<-structure(list(Sample = c("1749742002_A", "1749742086_A", "1749742184_A"
), Call.Rate = c(0.9995, 0.9992, 0.999), Study = c(133, 133,
133), Ethnicity = c("Adygei", "Maya", "Adygei")), .Names = c("Sample",
"Call.Rate", "Study", "Ethnicity"), row.names = c(NA, 3L), class = "data.frame")
结果
Sample Call.Rate Study Ethnicity
1749742002_A:1749742086_A 0.9995:0.9992 133:133 Adygei:Maya
1749742086_A:1749742002_A 0.9992:0.9995 133:133 Maya:Adygei
1749742086_A:1749742184_A 0.9992:0.9990 133:133 Maya:Adygei
1749742184_A:1749742002_A 0.9990:0.9995 133:133 Adygei:Adygei
依旧......
答案 0 :(得分:1)
我们可以使用
data.frame(lapply(mydf, function(x) if(length(unique(x)) >1)
do.call(paste, c(expand.grid(x,x), sep=":"))
else paste(x[1], x[1], sep=":")))
答案 1 :(得分:0)
这是一个版本,使用中间数据框,以便更容易理解这些步骤 如果订单很重要,可能需要调整最终的排序
# slightly cleaner data creation
mydf<-data.frame(
Sample = c("1749742002_A", "1749742086_A", "1749742184_A"),
Call.Rate = c(0.9995, 0.9992, 0.999),
Study = c(133, 133, 133),
Ethnicity = c("Adygei", "Maya", "Adygei"))
require(dplyr)
# use dplyr::lead to create a dataframe offset by 1 row
# and prefix the column names with "y.
mydf_lead <- data.frame(lapply(mydf, lead))
names(mydf_lead) <- paste0("y.", names(mydf))
# cbind the original wwith the lead df
mydf2 <- cbind(mydf, mydf_lead) %>% filter(!is.na(y.Sample))
# create the a:b and b:a variations as seprate data frames -- fix oclumn names
mydf_ab <- data.frame(lapply(1:ncol(mydf), function(i) {paste(mydf2[,i], ":", mydf2[,i+ncol(mydf)])}))
mydf_ba <- data.frame(lapply(1:ncol(mydf), function(i) {paste(mydf2[,i+ncol(mydf)], ":", mydf2[,i])}))
names(mydf_ab) <- names(mydf_ba) <- names(mydf)
# rbind the results, and sort
result <- rbind(mydf_ab, mydf_ba) %>%
arrange(Sample)
result
Sample Call.Rate Study Ethnicity
1 1749742002_A : 1749742086_A 0.9995 : 0.9992 133 : 133 Adygei : Maya
2 1749742086_A : 1749742184_A 0.9992 : 0.999 133 : 133 Maya : Adygei
3 1749742086_A : 1749742002_A 0.9992 : 0.9995 133 : 133 Maya : Adygei
4 1749742184_A : 1749742086_A 0.999 : 0.9992 133 : 133 Adygei : Maya