使用dplyr重命名没有初始名称的矩阵列
我正在尝试重命名dplyr中没有名称的矩阵的列:使用dplyr重命名没有初始名称的矩阵列,r,dplyr,R,Dplyr,我正在尝试重命名dplyr中没有名称的矩阵的列: set.seed(1234) v1 <- table(round(runif(50,0,10))) v2 <- table(round(runif(50,0,10))) library(dplyr) bind_rows(v1,v2) %>% t [,1] [,2] 0 3 4 1 1 9 2 8 6 3 11 7 5 7 8 6 7
set.seed(1234)
v1 <- table(round(runif(50,0,10)))
v2 <- table(round(runif(50,0,10)))
library(dplyr)
bind_rows(v1,v2) %>%
t
[,1] [,2]
0 3 4
1 1 9
2 8 6
3 11 7
5 7 8
6 7 1
7 3 4
8 6 3
9 3 6
10 1 NA
4 NA 2
这些都不管用
我知道基本的R方法(
colnames(obj)这一个与magrittr
:
library(dplyr)
bind_rows(v1,v2) %>%
t %>%
magrittr::set_colnames(c("new1", "new2"))
这个带有magrittr的
library(dplyr)
bind_rows(v1,v2) %>%
t %>%
magrittr::set_colnames(c("new1", "new2"))
为了使用rename
您需要某种列表(如数据帧或TIBLE)。因此您可以做两件事。您可以转换为TIBLE
并使用rename
或使用colnames
并保持结构不变,即
new_d <- bind_rows(v1,v2) %>%
t() %>%
as.tibble() %>%
rename('A' = 'V1', 'B' = 'V2')
#where
str(new_d)
#Classes ‘tbl_df’, ‘tbl’ and 'data.frame': 11 obs. of 2 variables:
# $ A: int 3 1 8 11 7 7 3 6 3 1 ...
# $ B: int 4 9 6 7 8 1 4 3 6 NA ...
Or
new_d1 <- bind_rows(v1,v2) %>%
t() %>%
`colnames<-`(c('A', 'B'))
#where
str(new_d1)
# int [1:11, 1:2] 3 1 8 11 7 7 3 6 3 1 ...
# - attr(*, "dimnames")=List of 2
# ..$ : chr [1:11] "0" "1" "2" "3" ...
# ..$ : chr [1:2] "A" "B"
new\u d%
t()%>%
as.tible()%>%
重命名('A'='V1','B'='V2')
#在哪里
str(纽约)
#“tbl_df”、“tbl”和“data.frame”类:11个obs,共2个变量:
#$A:INT3 1 8 11 7 7 3 6 3 1。。。
#$B:int 4 9 6 7 8 1 4 3 6 NA。。。
或
新单位首被告%
t()%>%
`colnames为了使用rename
您需要某种列表(如数据帧或TIBLE)。因此您可以做两件事。您可以转换为TIBLE
并使用rename
或使用colnames
并保持结构不变,即
new_d <- bind_rows(v1,v2) %>%
t() %>%
as.tibble() %>%
rename('A' = 'V1', 'B' = 'V2')
#where
str(new_d)
#Classes ‘tbl_df’, ‘tbl’ and 'data.frame': 11 obs. of 2 variables:
# $ A: int 3 1 8 11 7 7 3 6 3 1 ...
# $ B: int 4 9 6 7 8 1 4 3 6 NA ...
Or
new_d1 <- bind_rows(v1,v2) %>%
t() %>%
`colnames<-`(c('A', 'B'))
#where
str(new_d1)
# int [1:11, 1:2] 3 1 8 11 7 7 3 6 3 1 ...
# - attr(*, "dimnames")=List of 2
# ..$ : chr [1:11] "0" "1" "2" "3" ...
# ..$ : chr [1:2] "A" "B"
new\u d%
t()%>%
as.tible()%>%
重命名('A'='V1','B'='V2')
#在哪里
str(纽约)
#“tbl_df”、“tbl”和“data.frame”类:11个obs,共2个变量:
#$A:INT3 1 8 11 7 7 3 6 3 1。。。
#$B:int 4 9 6 7 8 1 4 3 6 NA。。。
或
新单位首被告%
t()%>%
`colnames…%%>%as.tibble()%%>%rename(…)
应该可以。甚至绑定行(v1,v2)%%>%t()%%`colnamesdplyr::rename
需要names
,而不是colnames
,因此可以使用data.frame
或tibble
。然后,您可以使用rename
,或者,可能更方便,也可以使用管道,setNames
。一个简单的as.data.frame
就可以实现这一点,并且您拥有了列V1
&V2
。您有一个矩阵。您需要将其转换为data.frame或tibble。如果按照Sotos的建议将其转换为tibble,您将看到V1和V2作为列名。如果您将数据转换为data frame,您将看到X1和X2作为列名。因此,对于rename()谢谢大家的快速回答。我喜欢colnames@Sotos,如果您愿意,请添加您的注释作为答案,我会接受它。..%>%as.tibble()%%>%rename(…)
应该可以。或者甚至绑定行(v1,v2)%%>%t()%%`colnamesdplyr::rename
需要names
,而不是colnames
,因此可以使用data.frame
或tibble
。然后,您可以使用rename
,或者,可能更方便,也可以使用管道,setNames
。一个简单的as.data.frame
就可以实现这一点,并且您拥有了列V1
&V2
。您有一个矩阵。您需要将其转换为data.frame或tibble。如果按照Sotos的建议将其转换为tibble,您将看到V1和V2作为列名。如果您将数据转换为data frame,您将看到X1和X2作为列名。因此,对于rename()谢谢大家的快速回答。我喜欢colnames@Sotos,如果您愿意,添加您的评论作为答案,我将接受。