【问题标题】:looping to concatenate string循环连接字符串
【发布时间】:2016-12-15 09:33:25
【问题描述】:

很抱歉提出一个基本问题。我尝试在以下链接中寻找答案,但没有运气

How to concatenate strings in a loop?

How to concatenate strings in a loop?

C concatenate string with int in loop

所以,这是一个可重现的例子。我有一个名为 house 的列表,即

house <- c("Dining Room", "Drawing Room", "Number of Bathrooms", "5", "Number of Bedroom", "5", "Number of Kitchens", "1")

房屋列表中的每个元素都是字符。现在我想创建另一个列表,如果列表元素的字符长度为一个(代表一个数字),那么它应该与前一个字符串元素连接。这是我期待的输出。

"Dining Room", "Drawing Room", "Number of Bathrooms 5", "Number of Bedroom 5", "Number of Kitchens 1"

我尝试运行一个循环,但输出与我预期的不相似。

for(i in house){ if(!is.na(nchar(house[i])) == 1) { cat(i,i-1) } else{ print(i) } }

【问题讨论】:

  • 我不得不说,这对于您的数据来说是非常奇怪的。如果可能的话,我会非常努力地避免获取此类数据:由于必须有一些进程生成这些数据,我建议更改该进程以生成不同的、逻辑上一致的格式的数据。
  • 例如,一个数字可以是22(2 个字符长度),不是吗?无论哪种方式,您都可以通过 indx <- which(nchar(house) == 1) ; house[indx - 1] <- paste(house[indx - 1], house[indx]) ; house[-indx] 将其完全矢量化,例如

标签: r string loops concatenation


【解决方案1】:

有多种方法可以做到这一点。下面是一个。如果有任何不清楚的地方,请告诉我。

house <- c("Dining Room", "Drawing Room", "Number of Bathrooms", "5", 
           "Number of Bedroom", "5", "Number of Kitchens", "1")

# helper function that determines if x is a numeric character
isNumChar = function(x) !is.na(suppressWarnings(as.integer(x)))
isNumChar('3') # yes!
isNumChar('Hello World') # no

foo = function(x) {
  # copy input
  out = x
  # get indices that are numeric characters
  idx = which(isNumChar(x)) 
  # paste those values to the value before them
  changed = paste(x[idx - 1], x[idx])
  # input changes over original values
  out[idx - 1] = changed
  # remove numbers
  out = out[-idx] 
  # return output
  return(out)
}

foo(house)
[1] "Dining Room"           "Drawing Room"          "Number of Bathrooms 5"
[4] "Number of Bedroom 5"   "Number of Kitchens 1"

【讨论】:

  • 你不需要循环。你可以简单地做idx &lt;- which(isNumChar(house)),这个解决方案看起来太熟悉了
猜你喜欢
  • 2017-12-18
  • 1970-01-01
  • 2015-12-16
  • 2015-07-27
  • 2013-07-07
  • 2016-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多