通过在r中的组合中添加新字母来创建dataframe
我必须创建一个具有字符组合的数据帧。我有3个字符,比如x1、x2和x3。我上一个数据帧的代码是-通过在r中的组合中添加新字母来创建dataframe,r,dataframe,combinations,R,Dataframe,Combinations,我必须创建一个具有字符组合的数据帧。我有3个字符,比如x1、x2和x3。我上一个数据帧的代码是- gain<-do.call(rbind, lapply(2:3, function(x) { do.call(rbind, combn(3, x, function(y) { data.frame(A = paste(y, collapse = ""), B = paste(c("", y), collapse = "x"),
gain<-do.call(rbind, lapply(2:3, function(x) {
do.call(rbind, combn(3, x, function(y) {
data.frame(A = paste(y, collapse = ""),
B = paste(c("", y), collapse = "x"),
stringsAsFactors = FALSE)
}, simplify = FALSE))
}))
> gain
A B
1 12 x1x2
2 13 x1x3
3 23 x2x3
4 123 x1x2x3
我办不到。如果有人帮助我,我将不胜感激
tmp = gsub("(x(\\d))", "b\\2\\1\\+", gain$B)
substring(tmp, 1, nchar(tmp) - 1)
#[1] "b1x1+b2x2" "b1x1+b3x3" "b2x2+b3x3" "b1x1+b2x2+b3x3"
或者如果您想从A开始
tmp = gsub("(\\d)", "b\\1x\\1\\+", gain$A)
substring(tmp, 1, nchar(tmp) - 1)
#[1] "b1x1+b2x2" "b1x1+b3x3" "b2x2+b3x3" "b1x1+b2x2+b3x3"
或者如果您想从A开始
tmp = gsub("(\\d)", "b\\1x\\1\\+", gain$A)
substring(tmp, 1, nchar(tmp) - 1)
#[1] "b1x1+b2x2" "b1x1+b3x3" "b2x2+b3x3" "b1x1+b2x2+b3x3"
带有
strsplit
和paste
gain$B <- sapply(strsplit(gain$B, "(?<=\\d)(?=x)", perl = TRUE),
function(x) paste(paste0("b",
unlist(regmatches(x, gregexpr("\\d+", x)))), x, collapse="+", sep=""))
gain$B
#[1] "b1x1+b2x2" "b1x1+b3x3" "b2x2+b3x3" "b1x1+b2x2+b3x3"
数据
gain带有strsplit
和粘贴的选项
gain$B <- sapply(strsplit(gain$B, "(?<=\\d)(?=x)", perl = TRUE),
function(x) paste(paste0("b",
unlist(regmatches(x, gregexpr("\\d+", x)))), x, collapse="+", sep=""))
gain$B
#[1] "b1x1+b2x2" "b1x1+b3x3" "b2x2+b3x3" "b1x1+b2x2+b3x3"
数据
增益
gain <- structure(list(A = c(12L, 13L, 23L, 123L), B = c("x1x2", "x1x3",
"x2x3", "x1x2x3")), class = "data.frame", row.names = c("1",
"2", "3", "4"))