2017-03-23 46 views
0

我有下表。我需要通過結合「StateC」列和「CountyC」列中的數字來獲得如下所示的輸出,但總共保留5位數字。 (請參閱輸出表中的列ID)粘貼時保持零位

如何在R中實現此目的?

在此先感謝。

表1:

Year State StateC County CountyC Yield 
1910 NE  1  Adams 1  10.1 
1910 NE 31  Arthur 10  20.5 
1910 NE 31  Boone 201  30.0 

輸出:

Year State StateC County CountyC Yield ID 
1910 NE  1  Adams 1  10.1 31001 
1910 NE 31  Arthur 10  20.5 31010 
1910 NE 31  Boone 201  30.0 31201 
+0

'sprintf()'可以做到這一點。 'Table1 $ ID < - sprintf(「%02d%03d」,Table1 $ StateC,Table1 $ CountyC)' – jogo

+0

我是R新手。你能告訴我怎麼做嗎? – user3408139

+1

檢查'?sprintf'並告訴我們你試過的是什麼 – ekstroem

回答

4

這是sprintf()任務:

Table1 <- read.table(header=TRUE, text= 
'Year State StateC County CountyC Yield 
1910 NE 31  Adams 1  10.1 
1910 NE 31  Arthur 10  20.5 
1910 NE 31  Boone 201  30.0') 
Table1 
Table1$ID <- sprintf("%02d%03d", Table1$StateC, Table1$CountyC) 
Table1 
# Year State StateC County CountyC Yield ID 
# 1 1910 NE  31 Adams  1 10.1 31001 
# 2 1910 NE  31 Arthur  10 20.5 31010 
# 3 1910 NE  31 Boone  201 30.0 31201 
+0

如果我有1位數的「StateC」,該怎麼辦? – user3408139

+0

'sprintf(「%02d%03d」,1,22)'給出「01022」https://stat.ethz.ch/R-manual/R-devel/library/base/html/sprintf.html – jogo

0

直接回答標題中的問題的方法是使用str_pad來自stringr包裝:

Table1$ID = with(Table1,paste(StateC,str_pad(CountyC,3,pad="0"),sep="")) 

函數調用str_pad(CountyC,3,pad="0")墊在CountyC列中的數字,使得它們0填充到具有長度3的@jogo更簡潔(和值得被接受)的sprintf()溶液,但如果是新的R和預期,你會做大量的字符串操作的則是很好的瞭解stringr

0

我們能做到這一點算術

Table1$ID <- with(Table1, 1e3*(StateC+CountyC/1e3)) 
Table1$ID 
#[1] 31001 31010 31201 

或者作爲@MatthewLundberg建議,是另一個s它的變體是

Table1$ID <- with(Table1, 1e3*StateC + CountyC) 
+1

簡單: '1e3 * StateC + CountyC' –