循环以连接字符串

时间:2016-08-09 11:04:59

标签: r string loops concatenation

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

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")

房屋清单中的每个元素都是字符。现在我想创建另一个列表,如果列表的元素的字符长度为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) } }

1 个答案:

答案 0 :(得分: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"