【问题标题】:Nested For loop in R with error "numerical expression has 2 elements: only the first used"R中的嵌套For循环错误“数值表达式有2个元素:只有第一个使用”
【发布时间】:2020-10-22 15:09:32
【问题描述】:

我正在尝试使用 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"

这里发生了 2 件事不起作用。一个是启动的 var output 使用第一个模式的长度(长度 = 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")

【问题讨论】:

  • c("hij", "ijk", "jkl", "klm", "lmn", "mno") 不是预期的结果吗?如果不是,输出应该是什么样子?
  • vector 使用“double”作为“numeric”的同义词。您将字符串放在双向量中,您应该将output 初始化为vector("character", ...)。 (但实际上似乎可能需要list()?)
  • 是的,好点@flo!预期的结果是两个字符串的组合。理想情况下,我想将它作为附加列添加到数据框a,因此类似于a$combo &lt;- output,其中输出为 [1] "abc" "bcd" "cde" "def" [2] "hij" " ijk" "jkl" "klm" "lmn" "mno"
  • 感谢@GregorThomas。将vector 更改为列表后,我得到如下输出,这不是我的意图。从vector("double",... 更改为vector("character",... 后,我仍然会收到错误消息,但是无论如何进行此编辑是有意义的。 [[1]] [1] "hij" [[2]] [1] "ijk" [[3]] [1] "jkl" [[4]] [1] "klm" [[5]] [ 1]“lmn”[[6]][1]“mno”

标签: r for-loop nested-for-loop


【解决方案1】:
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 建议的那样。

【讨论】:

    猜你喜欢
    • 2014-06-04
    • 2018-02-07
    • 2020-06-15
    • 1970-01-01
    • 2018-09-16
    • 2012-09-03
    • 2021-08-17
    • 2020-07-19
    • 2020-12-27
    相关资源
    最近更新 更多