2016-09-20 3 views
2

私はデータが設定されている(例えば)test担当者()関数はエラーを投げている

私はその test$z以外 test$xを反映する変数 test$zを、作成したい
test <- data.frame(x = c(90, 801, 6457, 92727), y = rep("test", 4)) 
print(test) 
     x y 
1 90 test 
2 801 test 
3 6457 test 
4 92727 test 

は常に10です文字の長さは、ゼロで空白を埋める。だから、結果のデータ・フレームは次のようになります。

print(test) 
     x y   z 
1 90 test 0000000090 
2 801 test 0000000801 
3 6457 test 0000006457 
4 92727 test 0000092727 

私は、以下の機能が私に私が探している結果与えるだろうと思った:

test$z <- paste0(as.character(rep(0, 10-nchar(as.character(test$x)))), as.character(test$x)) 

をしかし、それはrepに次のエラーをバックキック機能:私はtest$zを取得するために、担当者の機能または任意の他のソリューションと異なり何ができるかの

Error in rep(0, 10 - nchar(as.character(test$x))) :
invalid 'times' argument

任意のアイデア?

+2

あなたはsprintfのを使用することができます。 – Roland

+0

または 'formatC(テスト$ x、フラグ= '0'、数字= 10、幅= 10) ' – rawr

答えて

4

問題はrep(0, 10-nchar(as.character(test$x)))にあります。第2引数は、times引数のベクトルです。基本的に、これはエラーがスローされます。その代わり

rep(0, c(9, 8, 7, 4)) 

、あなたが行う必要があります:2つのベクトルの長さが同じである

rep(c(0,0,0,0), c(9, 8, 7, 4)) 

します。 xc(0,0,0,0)で、timesc(9, 8, 7, 4)である私たちの例では

If times consists of a single integer, the result consists of the whole input repeated this many times. If times is a vector of the same length as x (after replication by each), the result consists of x[1] repeated times[1] times, x[2] repeated times[2] times and so on.

、:

?repは、と述べています。コメントの中で

test$z <- sapply(test$x, function(x) paste0(paste0(rep(0,10-nchar(x)),collapse = ""),x)) 

#  x y   z 
#1 90 test 0000000090 
#2 801 test 0000000801 
#3 6457 test 0000006457 
#4 92727 test 0000092727 
2

を@Roland素晴らしいアイデアですsprintf()を、言及:

あなたが行うことができます。そして、@ m0h3nは彼の答えでrep()の問題を説明しました。両方に代わる方法があります。

あなたはそのx引数timesの長さをリサイクルする新しい基本機能strrep()、とrep()を置き換えることができます。あなたの場合はうまくいくようです。

strrep(0, 10 - nchar(test$x)) 
# [1] "00000000" "0000000" "000000" "00000" 

test$xの先頭に貼り付けて完了です。それはすべて内部的に行われているので、何もする必要はありません。

paste0(strrep(0, 10 - nchar(test$x)), test$x) 
# [1] "0000000090" "0000000801" "0000006457" "0000092727" 

注:strrep()はRバージョン3.3.1で導入されました。

2

これまでのところ、良い答えがいくつかあります。

お楽しみのために、すでに知っている可能性のある関数を使って行うための、「クイックダーティ」な方法の例です。

test$z <- substr(paste0('0000000000', as.character(test$x)), 
       nchar(test$x), 
       10+nchar(test$x)) 

ちょうどあなたが各エントリに(例えば、10)を必要とし、サブますより多くのゼロを貼り付けます。

P.S.代わりに書き込むことにより、長さNの文字列を使用して、上記のコードではゼロの文字列を置き換えることができます:

paste0(rep(0, n), collapse='') 
+0

巧妙な解決策! – bshelt141

関連する問題