2016-09-20 41 views
2

我已設置數據(比如說)test代表()函數使用可變關於「倍」被引發錯誤

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 

我想創建變量test$z鏡像test$x,不同之處在於test$z始終爲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踢回了以下錯誤功能:

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

什麼,我可以與代表功能或任何其他解決方案有什麼不同獲得test$z任何想法?

+2

您可以用sprintf。 – Roland

+0

或'formatC(test $ x,flag ='0',digits = 10,width = 10)' – rawr

回答

4

該問題源於rep(0, 10-nchar(as.character(test$x))),其中第二個參數是一個向量,它是參數times。基本上,這將引發一個錯誤:

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

相反,你應該做的:

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

,其中兩個向量的長度是相同的。

?rep指出:

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.

在我們的例子中,xc(0,0,0,0)timesc(9, 8, 7, 4)

你可以這樣做:

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()的問題。這是兩種選擇。

你可以在新的基本功能strrep(),這將回收其x說法times長度替換rep()。它似乎很適合你的情況。

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

所以我們只是粘貼到的test$x前,我們就大功告成了。因爲它都是在內部完成的,所以不需要任何as.character強制。

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.您可以通過,而不是寫長度爲ň的字符串替換零的字符串在上述代碼:

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

巧妙的解決方案! – bshelt141

相關問題