0

我正在尝试使用 R 中的嵌套 for 循环在字符串中打印 3 个连续字符的组合。代码确实打印了组合,但是我收到一个错误,即仅针对其中一个元素而不是数据框中的每一行执行此操作。

x <- data.frame(Pattern = c("abcdef", "hijklmnop"), id = 1:2)

output <- vector("character", length(x$Pattern))

for (i in 1:nrow(x)) {  

  file <- x$Pattern[i]

  for (j in 1:(str_length(x$Pattern))) {
    output[j] <- substr(file, j, j+2)
  }

}

numerical expression has 2 elements: only the first usednumerical expression has 2 elements: only the first used
> 
> output
[1] "hij" "ijk" "jkl" "klm" "lmn" "mno"

这里发生了两件事不起作用。一个是output启动的 var 使用第一个模式的长度(长度 = 6)并基于该长度打印组合,但是我正在寻找字符串长度(长度 = 9)的输出。预期的输出如下,没有使用嵌套的 for 循环。

  for (j in 1:9) {
    
    output[j] <- substr(file, j, j+2)
    
  }

output
[1] "hij" "ijk" "jkl" "klm" "lmn" "mno" "nop" "op"  "p"  

我进一步修剪它,以便每个字符串只有 3 个连续字符的组合列表。

list(output[1:(length(output)-3)])
[[1]]
[1] "hij" "ijk" "jkl" "klm" "lmn" "mno"

我遇到的第二个问题是输出仅打印列表中第二个字符串的组合。我已尝试更改1:nrow(a)seq_alonglength(a)按照其他帖子中的建议进行更改,但这不起作用。预期的输出如下。

a$combo <- output

a$combo
[1] c("abc","bcd","cde","def") c("hij","ijk","jkl","klm","lmn","mno")

4

1 回答 1

0
x <- data.frame(Pattern = c("abcdef", "hijklmnop"), id = 1:2)

# number of additional letters in individual character string
add_letters = 2

library(stringr)

output = list()


for (i in 1:nrow(x)) {  
    
    file <- x$Pattern[i]
    
    l = list()
    
    for (j in 1:(str_length(x$Pattern[i])-add_letters)) {
        
        l[j] <- c(substr(file, j, j+add_letters))
    
    }
    
    output[[i]] = l 
    
}

x$combo = output

带有列表的解决方案 - 正如 Gregor Thomas 所建议的那样。

于 2020-10-23T15:05:48.597 回答