2016-08-09 5 views
0

を連結するループ。私は、以下のリンクで答えを探してみましたが、それで運は、基本的な質問をして申し訳ありません文字列

How to concatenate strings in a loop?

How to concatenate strings in a loop?

C concatenate string with int in loop

で、ここに再現可能な例ですしました。私は家のすなわち

家のリスト内のすべての要素が文字である

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

と呼ばれるリストをしました。今度は別のリストを作成します。listの要素の長さが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) } }

+0

私は、あなたのデータが最初に存在するのは非常に奇妙なことです。私はこのようなデータを得ることを避けるために非常に努力したいと思います。このデータを生成するプロセスが必要なので、そのプロセスを変更して、論理的に一貫性のある別のフォーマットでデータを生成することをお勧めします。 –

+3

数字は「22」(2文字の長さ)、いいえ?どちらにしても、 'indx < - which(nchar(house)== 1)を実行することで、これを完全にベクトル化できます。 house [indx - 1] < - ペースト(house [indx - 1]、house [indx]); house [-indx] '、例えば –

答えて

1

これを行うには、複数の方法があります。以下は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" 
+1

あなたはループをしません。単純に 'idx < - which(isNumChar(house))'を行うことができます。 –

関連する問題