如何从 R 中的 df 中的列粘贴数字 + 1
How to paste a number + 1 from a column in a df in R
我有一个包含一些信息的 df,我在其中创建了一些测试用例。我想将测试用例一起粘贴到一个 SQL 句子中,并为每个案例的特定数字添加 +1。
我首先创建测试用例:
z <- data.frame(X = c('1','0', '1','1', '1'), Y = c('1','0', '1','0', '1'))
z <- as.data.frame(sapply(1:ncol(z), function(x)
ifelse(z[[x]] != '?', paste(colnames(z)[x], ' = ', z[[x]]),'')))
z$testcases <- do.call(paste, c(z, sep=" AND "))
我尝试通过我创建的 +1 函数将 1 添加到数字“1200”,但是我不知道如何让 R 使用第一个数字,然后将数字 + 1 粘贴到下一行:
add_1 <- function(x) {
y <- x+1
return(y)
}
id_str <- 1200
z$test_sql <- paste0("WHEN ", z$testcases , " THEN ", "'", id_str + add_1(id_str), " passed","'")
#expected output for z$test_sql:
z$test_sql
[1] "WHEN X = 1 AND Y = 1 AND X = 1 & Y = 1 THEN '1200 passed'"
[2] "WHEN X = 0 AND Y = 0 AND X = 0 & Y = 0 THEN '1201 passed'"
[3] "WHEN X = 1 AND Y = 1 AND X = 1 & Y = 1 THEN '1202 passed'"
[4] "WHEN X = 1 AND Y = 0 AND X = 1 & Y = 0 THEN '1203 passed'"
[5] "WHEN X = 1 AND Y = 1 AND X = 1 & Y = 1 THEN '1204 passed'"
z$test_sql <- paste0("WHEN ",z$V1," AND ",z$V2," AND ",z$testcases," THEN ","'",id_str+0:(nrow(z)-1)," passed","'")
test_sql
1 WHEN X = 1 AND Y = 1 AND X = 1 AND Y = 1 THEN '1200 passed'
2 WHEN X = 0 AND Y = 0 AND X = 0 AND Y = 0 THEN '1201 passed'
3 WHEN X = 1 AND Y = 1 AND X = 1 AND Y = 1 THEN '1202 passed'
4 WHEN X = 1 AND Y = 0 AND X = 1 AND Y = 0 THEN '1203 passed'
5 WHEN X = 1 AND Y = 1 AND X = 1 AND Y = 1 THEN '1204 passed'
我有一个包含一些信息的 df,我在其中创建了一些测试用例。我想将测试用例一起粘贴到一个 SQL 句子中,并为每个案例的特定数字添加 +1。
我首先创建测试用例:
z <- data.frame(X = c('1','0', '1','1', '1'), Y = c('1','0', '1','0', '1'))
z <- as.data.frame(sapply(1:ncol(z), function(x)
ifelse(z[[x]] != '?', paste(colnames(z)[x], ' = ', z[[x]]),'')))
z$testcases <- do.call(paste, c(z, sep=" AND "))
我尝试通过我创建的 +1 函数将 1 添加到数字“1200”,但是我不知道如何让 R 使用第一个数字,然后将数字 + 1 粘贴到下一行:
add_1 <- function(x) {
y <- x+1
return(y)
}
id_str <- 1200
z$test_sql <- paste0("WHEN ", z$testcases , " THEN ", "'", id_str + add_1(id_str), " passed","'")
#expected output for z$test_sql:
z$test_sql
[1] "WHEN X = 1 AND Y = 1 AND X = 1 & Y = 1 THEN '1200 passed'"
[2] "WHEN X = 0 AND Y = 0 AND X = 0 & Y = 0 THEN '1201 passed'"
[3] "WHEN X = 1 AND Y = 1 AND X = 1 & Y = 1 THEN '1202 passed'"
[4] "WHEN X = 1 AND Y = 0 AND X = 1 & Y = 0 THEN '1203 passed'"
[5] "WHEN X = 1 AND Y = 1 AND X = 1 & Y = 1 THEN '1204 passed'"
z$test_sql <- paste0("WHEN ",z$V1," AND ",z$V2," AND ",z$testcases," THEN ","'",id_str+0:(nrow(z)-1)," passed","'")
test_sql
1 WHEN X = 1 AND Y = 1 AND X = 1 AND Y = 1 THEN '1200 passed'
2 WHEN X = 0 AND Y = 0 AND X = 0 AND Y = 0 THEN '1201 passed'
3 WHEN X = 1 AND Y = 1 AND X = 1 AND Y = 1 THEN '1202 passed'
4 WHEN X = 1 AND Y = 0 AND X = 1 AND Y = 0 THEN '1203 passed'
5 WHEN X = 1 AND Y = 1 AND X = 1 AND Y = 1 THEN '1204 passed'