Mina
Mina

Reputation: 307

How to combine multiple columns in R

Suppose I have this data set:

     age      height       weight
   "1/2/3"  "12/15/18"   "30/40/37"

How can I have a dataset like a dataset below?

   age height weight
    1    12     30
    2    15     40
    3    18     37

And what if my dataset was like this:

  name     age      height       weight
 "Jack"  "1/2/3"  "12/15/18"   "30/40/37"

I want to have a data set like below:

    name  age height weight
   "Jack"  1    12     30
   "Jack"  2    15     40
   "Jack"  3    18     37

How can I do this?

Upvotes: 1

Views: 142

Answers (2)

benson23
benson23

Reputation: 19142

If you don't mind using external package, you can use separate_rows() from the tidyr package.

library(tidyverse)

df %>% separate_rows(-name, sep = "/")

# A tibble: 3 × 4
  name  age   height weight
  <chr> <chr> <chr>  <chr> 
1 Jack  1     12     30    
2 Jack  2     15     40    
3 Jack  3     18     37    

Upvotes: 5

Allan Cameron
Allan Cameron

Reputation: 174478

If your data is in data frame format like this:

df <- data.frame(age = '1/2/3', height = '12/15/18', weight = '30/40/37')

df
#>     age   height   weight
#> 1 1/2/3 12/15/18 30/40/37

You could do

as.data.frame(lapply(df, function(x) as.numeric(unlist(strsplit(x, '/')))))
#>   age height weight
#> 1   1     12     30
#> 2   2     15     40
#> 3   3     18     37

The same code will also work if your data is a named vector (it's not clear from the question what format your data is in, but the above code should work in either case as long as your data is called df)

Created on 2022-04-10 by the reprex package (v2.0.1)

Upvotes: 2

Related Questions