jeff
jeff

Reputation: 335

create multiple columns at once, depending on the number of columns of another df, with dplyr

I want to create with dplyr a df with n columns (depending on the number of columns of df data), where the root of the name is the same TIME. and first the column is equal to 1 in all rows, the second equal to 2 and so on. The number of rows is the same as data

data <- data.frame(ID=c(1:6), VALUE.1=c(2,5,7,1,3,5), VALUE.2=c(1,7,2,4,5,4), VALUE.3=c(9,2,6,3,4,4), VALUE.4=c(1,2,3,2,3,8))

And the first column of data as first column. This is what I'd like to have:

  ID  TIME.1 TIME.2 TIME.3 TIME.4
   1    1      2       3       4
   2    1      2       3       4
   3    1      2       3       4
   4    1      2       3       4
   5    1      2       3       4
   6    1      2       3       4

Now I'm doing:

T1 <- data.frame(ID=unique(data$ID), TIME.1=rep(1, length(unique(data$ID))), TIME.2=rep(2, length(unique(data$ID))), TIME.3=rep(3, length(unique(data$ID))), TIME.4=rep(4, length(unique(data$ID))) )

Upvotes: 1

Views: 78

Answers (2)

Ben
Ben

Reputation: 30474

Here is a base R approach that may give a similar result. This involves creating a matrix based on your other data.frame data, using its dimensions for column names and determining the number of rows. We subtract 1 from number of columns given the first ID column present.

nc <- ncol(data) - 1
nr <- nrow(data)

as.data.frame(cbind(
  ID = data$ID,
  matrix(1:nc, ncol = nc, nrow = nr, byrow = T, dimnames = list(NULL, paste0("TIME.", 1:nc)))
))

Output

  ID TIME.1 TIME.2 TIME.3 TIME.4
1  1      1      2      3      4
2  2      1      2      3      4
3  3      1      2      3      4
4  4      1      2      3      4
5  5      1      2      3      4
6  6      1      2      3      4

Upvotes: 0

benson23
benson23

Reputation: 19097

We can replace the column contents with the suffix in the column name, then rename the columns from VALUE.n to TIME.n.

library(dplyr)

data %>% 
  mutate(across(starts_with("VALUE"), ~sub("VALUE.", "", cur_column()))) %>% 
  rename_with(~sub("VALUE", "TIME", .x))

  ID TIME.1 TIME.2 TIME.3 TIME.4
1  1      1      2      3      4
2  2      1      2      3      4
3  3      1      2      3      4
4  4      1      2      3      4
5  5      1      2      3      4
6  6      1      2      3      4

Upvotes: 1

Related Questions