在字符列中添加0

时间:2018-10-16 14:05:47

标签: r

我有一个数据框,其中有一列字符值:

df1
Col1     Col2    
   A        1
   B        2
   C       11
   D      101
   E     1000

我有另一个数据集,其中也包含字符值,但是每个值都有5个数字,即使它是一个很小的数字,如下所示:

df2
Col1A     Col2    
   F     00001
   G     00002
   H     00011
   I     00101
   J     01000

如何在df1中添加0,以便可以将两个数据帧连接在一起?

预期输出:

df1
Col1      Col2     Col1A
   A     00001         F
   B     00002         G
   C     00011         H
   D     00101         I
   E     01000         J

2 个答案:

答案 0 :(得分:1)

数据:

read.table(text="Col1     Col2    
A        1
B        2
C       11
D      101
E     1000", colClasses=c("character", "character"), header=TRUE) -> xdf1

read.table(text="Col1A     Col2    
F     00001
G     00002
H     00011
I     00101
J     01000", colClasses=c("character", "character"), header=TRUE) -> xdf2

0个依赖库R:

setNames(merge(
  { xdf1$Col3 <- sprintf("%05s", xdf1$Col2) ; xdf1 },
  xdf2, by.x = "Col3", by.y = "Col2"
)[,c(2,1,4)], c("Col1", "Col2", "Col1A"))
##    Col1  Col2 Col1A
## 1    A 00001     F
## 2    B 00002     G
## 3    C 00011     H
## 4    D 00101     I
## 5    E 01000     J

xdf1$Col3 <- NULL # to preserve the original data frame

答案 1 :(得分:0)

喜欢吗?

 library(tidyverse)
 df1<-data.frame(Col1=c("A","B","C","D","E"),
                Col2=c(1,2,11,101,1000))

 df2<-data.frame(Col1=c("00001","00002","00011","00101","01000"),
                 Col2=c("F","G","H","I","J"))

 your_function=function(x){
   if(nchar(x)<5){
     x<-glue::collapse(c(rep("0",5-nchar(x)),x),sep="")
   }
   return(x)
 }
 df1%>%
   mutate(Col2=purrr::map_chr(Col2,your_function))%>%
   left_join(df2,by=c("Col2"="Col1"))
  Col1  Col2 Col2.y
1    A 00001      F
2    B 00002      G
3    C 00011      H
4    D 00101      I
5    E 01000      J