Azam Yahya
Azam Yahya

Reputation: 53

looping to concatenate string

Sorry for asking a basic question. I've tried looking for the answer in the following links but with no luck

How to concatenate strings in a loop?

How to concatenate strings in a loop?

C concatenate string with int in loop

So, here is a reproducible example. I've a list called house i.e

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

where every element in the house list is character. Now I want to create another list where if the element of list is of character length of one(representing a number) then it should concatenate with the previous string element. This is output I am expecting.

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

I have tried running a loop but the output is not similar to what I expect.

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

Upvotes: 0

Views: 2039

Answers (1)

Vandenman
Vandenman

Reputation: 3176

There are multiple ways to do this. Below is one. If anything is unclear, let me know.

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"

Upvotes: 1

Related Questions