方法一:
df1<-data.frame(A=1:5,B=2:6)
df2<-data.frame(A=1:5,B=2:6)
df3<-rbind(df1,df2)
row.names(df3)
[1] "1" "2" "3" "4" "5" "6" "7" "8" "9" "10"
方法二:
df1<-data.frame(matrix(data = c(1:5,2:6),
nrow = 5,
dimnames = list(c(1:5),c("A","B"))))
df2<-data.frame(matrix(data = c(1:5,2:6),
nrow = 5,
dimnames = list(c(1:5),c("A","B"))))
df3<-rbind(df1,df2)
row.names(df3)
[1] "1" "2" "3" "4" "5" "11" "21" "31" "41" "51"
我知道行名应该是唯一的值,我想知道为什么Mehtod1和方法2在行名中生成不同的结果?
在方法1中,行名是整数
df1 <- data.frame(A=1:5,B=2:6)
df2 <- data.frame(A=1:5,B=2:6)
dput(df1)
structure(list(A = 1:5, B = 2:6), class = "data.frame", row.names = c(NA,
-5L))
并且在
rbind
之后它们保持整数
df3 <- rbind(df1,df2)
dput(df3)
structure(list(A = c(1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L),
B = c(2L, 3L, 4L, 5L, 6L, 2L, 3L, 4L, 5L, 6L)), row.names = c(NA,
-10L), class = "data.frame")
在方法2中,行名是字符串
df1 <- data.frame(matrix(data = c(1:5,2:6),
nrow = 5,
dimnames = list(c(1:5),c("A","B"))))
df2 <- data.frame(matrix(data = c(1:5,2:6),
nrow = 5,
dimnames = list(c(1:5),c("A","B"))))
dput(df1)
structure(list(A = 1:5, B = 2:6), class = "data.frame", row.names = c("1",
"2", "3", "4", "5"))
并且在
rbind
之后它们也仍然保留原来的类,字符串
dput(df3)
structure(list(A = c(1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L),
B = c(2L, 3L, 4L, 5L, 6L, 2L, 3L, 4L, 5L, 6L)), row.names = c("1",
"2", "3", "4", "5", "11", "21", "31", "41", "51"), class = "data.frame")
字符串无法枚举,因此通过向字符串添加索引来使其唯一。