Merging string vectors into one, seperated by a comma

Hi!
I am having trouble with the rather easy problem of merging a few string vectors into one, seperating the entries with a comma. The problem can be boiled down to this:

 Fruit<-c("Banana", "Apple", "Banana", "Orange", "Appel")
Origin<-c("New Guinea", "China","Germany", "USA", "Germany")
Quality<-c("Good", "Bad", "Good", "Very bad", "Decent")
Price<-c(1,2,1,3,2)

Fruits<-data.frame(Fruit, Origin, Quality, Price)

how to get one dataframe, whose first coloumn's (let's call the coloumn xyz) first entry for example looks like this:
Banana, New Guinea, Good
while the second coloumn contains the price?

I have found this thread

, which contains the operation I need, and tried every method listed there, however I could not even reproduce the problem of the link, namely writing the string in C behind the strings in A and B. R always nags about something different, or does not even recognize entries at all. I have been replacing the dataframe data in the example with in this case Fruits and the coloumns A,B,C with the respective names of the coloumns of this example. For the first coloumn for example, I have tried Fruit, "Fruit" and Fruits$Fruit, nothing works. What am I doing wrong?

Is this what you are after?

library(tidyverse)

tibble(Fruit, Origin, Quality, Price) %>% 
  unite("joined", Fruit:Quality, sep = ", ")
  
# A tibble: 5 x 2
  joined                   Price
  <chr>                    <dbl>
1 Banana, New Guinea, Good     1
2 Apple, China, Bad            2
3 Banana, Germany, Good        1
4 Orange, USA, Very bad        3
5 Appel, Germany, Decent       2

See:

1 Like

Here are a few other options for you.

Fruit<-c("Banana", "Apple", "Banana", "Orange", "Appel")
Origin<-c("New Guinea", "China","Germany", "USA", "Germany")
Quality<-c("Good", "Bad", "Good", "Very bad", "Decent")
Price<-c(1,2,1,3,2)

Fruits<-data.frame(Fruit, Origin, Quality, Price)

Using base R

Fruits$xyz <- with(Fruits, paste(Fruit, Origin, Quality, sep = ", "))
Fruits[, c("xyz", "Price")]

                       xyz Price
1 Banana, New Guinea, Good     1
2        Apple, China, Bad     2
3    Banana, Germany, Good     1
4    Orange, USA, Very bad     3
5   Appel, Germany, Decent     2

Using dplyr

library(dplyr)

Fruits %>%
  mutate(xyz = paste(Fruit, Origin, Quality, sep = ", ")) %>%
  select(xyz, Price)

                       xyz Price
1 Banana, New Guinea, Good     1
2        Apple, China, Bad     2
3    Banana, Germany, Good     1
4    Orange, USA, Very bad     3
5   Appel, Germany, Decent     2
2 Likes

Thank you both, that should work! :smiley:

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.