问题描述
表一
col 1 col 2 col 3
1 0 2
3 2 1
5 3 2
表 2
col 1 col 2 col 3
1 2 3
2 3 1
3 1 2
我想要的输出是......
col1 col2 col3
11 02 23
32 23 11
53 31 22
解决方法
library(dplyr)
table1 <- tribble(
~col1,~col2,~col3,1,2,3,5,2)
table2 <- tribble(
~col1,2)
table3 <- table1 %>%
mutate(col1 = paste(table1$col1,table2$col1,sep = ""),col2 = paste(table1$col2,table2$col2,col3 = paste(table1$col3,table2$col3,sep = ""))
,
使用Map
:
table1[] <- Map(paste0,table1,table2)
table1
# col1 col2 col3
#1 11 02 23
#2 32 23 11
#3 53 31 22
如果列的类型相同,您也可以使用 as.matrix
而不使用 Map
。
table1[] <- paste0(as.matrix(table1),as.matrix(table2))
数据
table1 <- structure(list(col1 = c(1,5),col2 = c(0,3),col3 = c(2,2)),row.names = c(NA,-3L),class = "data.frame")
table2 <- structure(list(col1 = c(1,col2 = c(2,1),col3 = c(3,class = "data.frame")
,
这是一个简单的方法,使用 paste0
。未提供数据,因此使用 mtcars
数据:
df1 <- mtcars[,c(2,8,9)]
df2 <- mtcars[,c(9,10,11)]
names(df1) <- c("col1","col2","col3")
names(df2) <- c("col1","col3")
df3 <- data.frame("col1" = paste0(df1$col1,df2$col1),"col2" = paste0(df1$col2,df2$col2),"col3" = paste0(df1$col3,df2$col3))
head(df3)
col1 col2 col3
1 61 04 14
2 61 04 14
3 41 14 11
4 60 13 01
5 80 03 02
6 60 13 01