You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用两个向量作为指示器折叠行的实现方法

Solution for Collapsing Adjacent String Rows by Start/End Indices

Hey there! No worries about being a new poster—we've all been there 😊. Let's fix this for you.

The issue with your original code is that text[x:y] treats your start (x) and end (y) vectors as a single range instead of processing each pair of start-end positions individually. That's why you're not getting the two separate strings you want.

Correct Implementation Using Base R

We can use mapply() to iterate over each pair of start and end indices, collapse the corresponding text elements, then wrap the result in a data frame:

text <- c("cat", "dog", "house", "mouse", "street")
x <- c(1, 3)
y <- c(2, 5)

# Process each start-end pair and collapse the text
collapsed_strings <- mapply(function(start_idx, end_idx) {
  paste(text[start_idx:end_idx], collapse = " ")
}, x, y)

# Convert to data frame (keep strings as text, not factors)
result <- data.frame(collapsed_text = collapsed_strings, stringsAsFactors = FALSE)

# View the result
print(result)

This will output exactly what you're looking for:

collapsed_text
1              cat dog
2 house mouse street

Alternative Using purrr (Tidyverse Style)

If you prefer using the tidyverse, the map2_chr() function from purrr makes this even more concise:

library(purrr)

collapsed_strings <- map2_chr(x, y, ~paste(text[.x:.y], collapse = " "))
result <- data.frame(collapsed_text = collapsed_strings)

Both approaches work by handling each start-end pair separately: for each index i, they take text[x[i]:y[i]], collapse those elements into a single space-separated string, then collect all those strings into a vector that becomes the column of your data frame.

内容的提问来源于stack exchange,提问作者Jo el

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 16:33:10