R concatenate columns with added notations

Viewed 58

I am trying to select several columns from a data frame and then output them to an excel file. For the last column I want to concatenate several columns with notation added between.

data %>%
  select(Place = place, Time = time, Number = paste(number_2, "(", number_1, 
                                              ",", number_3, ")")) %>%
  openxlsx::write.xlsx(file = here("data"))

I am getting the error

object not found

If I include the dataframe

data %>%
  select(Place = place, Time = time, Number = paste(data$number_2, "(", data$number_1, 
                                              ",", data$number_3, ")")) %>%
  openxlsx::write.xlsx(file = here("data"))

I get the following error

Can't subset to columns that don't exist

A sample of the data is

Place   Time    Number 2    Number 1    Number 3
R1  T1  .5  .4  .7
R2  T1  .2  .1  .3
R1  T2  .4  .3  .6
R2  T2  .3  .2  .4

Thanks for any help!

1 Answers

You are attempting to access columns named number_2 etc., but these columns don’t exist in the sample data you’ve posted.

You need to use the correct column name: `Number 2`.

data %>%
  select(
    Place = place,
    Time = time,
    Number = paste(`Number 2`, "(", `Number 1`, ",", `Number 3`, ")")
  ) %>%
  openxlsx::write.xlsx(file = here("data"))

Note the backticks (`), which are needed around “non-syntactic” names in R code (in your case, because your column names contain spaces, which isn’t syntactically valid).

Related