I have an n x m matrix:
M<-matrix(0,nrow=3,ncol=4)
colnames(M)<-c("apple","banana","orange","cherry")
rownames(M)<-c("squash","water","milk")
I would like to replicate the columns of the matrix 5 times such that they will unique names. e.g. apple_1, apple_2,..., apple_4,..., banana_1, banana_2 etc.
I currently convert it to a tibble
and try a dplyr
method:
M %>% as_tibble() %>%
mutate(drinks=rownames(M)) %>%
pivot_longer(!sid,names_to = "fruit") %>%
slice(rep(1:n(), each=5)) %>%
pivot_wider(names_from=fruit,values_from=value) %>%
unnest()
But because it creates non-unique columns names, it seems to remove them when I convert it back to a wide format. Any help would be much appreciated
CodePudding user response:
Because data.frame
is just a list with extra attributes, you can use rep(x, each=5)
:
m <- matrix(0, nrow = 3, ncol = 5)
colnames(m) <- c("apple", "banana", "orange", "cherry", "pear")
rownames(m) <- c("squash", "water", "milk")
d <- as.data.frame(m)
as.data.frame(rep(d, each = 5))
#> apple apple.1 apple.2 apple.3 apple.4 banana banana.1 banana.2 banana.3
#> 1 0 0 0 0 0 0 0 0 0
#> 2 0 0 0 0 0 0 0 0 0
#> 3 0 0 0 0 0 0 0 0 0
#> banana.4 orange orange.1 orange.2 orange.3 orange.4 cherry cherry.1 cherry.2
#> 1 0 0 0 0 0 0 0 0 0
#> 2 0 0 0 0 0 0 0 0 0
#> 3 0 0 0 0 0 0 0 0 0
#> cherry.3 cherry.4 pear pear.1 pear.2 pear.3 pear.4
#> 1 0 0 0 0 0 0 0
#> 2 0 0 0 0 0 0 0
#> 3 0 0 0 0 0 0 0
CodePudding user response:
simple
M <-matrix(0,nrow=3,ncol=5)
colnames(M)<-c("apple","banana","orange","cherry","blackberry")
rownames(M)<-c("squash","water","milk")
M <- as.data.frame(M)
for(col_name in colnames(M)){
for(i in 1:5){
M[[paste0(col_name,'_',i)]] <- M[,col_name]
}
}
output
apple banana orange cherry blackberry apple_1 apple_2 apple_3 apple_4 apple_5 banana_1 banana_2 banana_3 banana_4 banana_5 orange_1 orange_2 orange_3
squash 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
water 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
milk 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
orange_4 orange_5 cherry_1 cherry_2 cherry_3 cherry_4 cherry_5 blackberry_1 blackberry_2 blackberry_3 blackberry_4 blackberry_5
squash 0 0 0 0 0 0 0 0 0 0 0 0
water 0 0 0 0 0 0 0 0 0 0 0 0
milk 0 0 0 0 0 0 0 0 0 0 0 0