I want to group 3 columns into one, separated by a comma in the R

Asked

Viewed 40 times

0

My dataset is like this:

    x   y   z
A 1.1 1.2 1.3
B 2.1 2.2 2.3

Using R, I want to group the 3 columns into one, separated by a comma.
I want you to stay like this:

              x   
A 1.1, 1.2, 1.3
B 2.1, 2.2, 2.3

Dice

dados <-
structure(list(x = c(1.1, 2.1), y = c(1.2, 2.2), z = c(1.3, 2.3
)), class = "data.frame", row.names = c("A", "B"))

2 answers

1

Use unite:

library(tidyr)

unite(data = dados, col = x, c(x, y, z), sep = ", ")

#                x
#  A 1.1, 1.2, 1.3
#  B 2.1, 2.2, 2.3

0

A base R solution with apply.

dados[[1]] <- apply(dados, 1, paste, collapse = ", ")
dados <- dados[1]

dados
#              x
#A 1.1, 1.2, 1.3
#B 2.1, 2.2, 2.3

Dice

dados <- read.table(text = "
    x   y   z
A 1.1 1.2 1.3
B 2.1 2.2 2.3
", header = TRUE)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.