0

I have a data.frame that looks like this

df = data.frame(ticker = c(rep("AAPL", 2), rep("MSFT",2)), 
                Date = c("2019", "2017", "2017", "2016"))

print(df)

  ticker Date
1   AAPL 2019
2   AAPL 2017
3   MSFT 2017
4   MSFT 2016

I would like to group by ticker and create a string for each row (Date). For example, I would like to create 2 strings that look like this.

x = "SomeOtherString"

"SomeOtherStringAAPL20192017"

"SomeOtherStringMSFT20172016"
Jordan Wrong
  • 1,205
  • 1
  • 12
  • 32

1 Answers1

1

You can use paste0 for each ticker like this :

library(dplyr)

df %>%
  group_by(ticker) %>%
  summarise(string = paste0(x, first(ticker), paste0(Date, collapse = '')))

#  ticker string                     
#  <chr>  <chr>                      
#1 AAPL   SomeOtherStringAAPL20192017
#2 MSFT   SomeOtherStringMSFT20172016

In base R :

transform(aggregate(Date~ticker, df, paste0, collapse = ''), 
          string = paste0(x, ticker, Date))
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213