2017-03-23 48 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' –