0

I'm trying to create a new variable in a dataframe in R, which will be a concatenation of the values of 31 character variables, but I don't want to explicitly refer to each of these variables by name, can anyone help me with this?

More specifically:

My dataframe is called 'TVs', with 35 variables, and I want to paste the values of character variables 2 to variable 31, which are all character variables.

I can do this for the first two variables with the following:

TVs2 <- TVs %>%
  mutate(productid = paste0(BRAND,`COMMON INTER CI`))

and that works, but I don't want to explicitly type in the 31 variable names, so instead I've created a list of the variables I want as follows:

names <- names(TVs)
names2 <- names[-c(1,32,33,34)]

and then I tried

TVs2 <- TVs %>%
  mutate(productid = str_c(unlist(names2)))

which gave me this error:

Error: Problem with `mutate()` column `productid`.
ℹ `productid = str_c(unlist(names2))`.
ℹ `productid` must be size 7521 or 1, not 30.

Can anybody help me out please?

krsinif
  • 1
  • 1
  • `TVs$productid <- do.call(paste0, TVs[2:31])` – Ronak Shah Sep 15 '21 at 04:37
  • A `tidyverse` approach `TVs %>% rowwise() %>% mutate(productid = str_c(c_across(-id),collapse = ","))` – Vinícius Félix Sep 15 '21 at 04:42
  • @ViníciusFélix - I'm presuming that runs `str_c` for every row, which will slow down markedly on large datasets. Probably better to use a vectorised function like: `mtcars %>% unite(productid, -mpg, sep=",")` as shown at the duplicate. – thelatemail Sep 15 '21 at 05:07

0 Answers0