Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate/paste together multiple columns in a dataframe

I have a dataframe with multiple observations (the amount and their names vary often) with minimum and maximum values. Example:

ID O1_min O1_max O2_min O2_max O3_min O3_max
A  1      2      1      2      1      2
B  1      2      1      2      1      2
C  1      2      1      2      1      2
D  1      2      1      2      1      2

I want to go through my data frame and transform all _min and _max columns in a _range column for each observation. So it would look like this:

ID O1_range O2_range O3_range
A  1:2      1:2      1:2
B  1:2      1:2      1:2
C  1:2      1:2      1:2
D  1:2      1:2      1:2

I was using paste() function but that won't solve my problem, once new columns can enter the dataframe at any time and I'd like to have a more automatic code.

like image 233
Huskir Avatar asked Mar 19 '26 14:03

Huskir


1 Answers

Suppose columns have the same naming convention, you can use purrr::map2_dfc().

Prepare data

library(dplyr)
library(purrr)
library(stringr)


data <- read_delim("ID O1_min O1_max O2_min O2_max O3_min O3_max
A  1      2      1      2      1      2
B  1      2      1      2      1      2
C  1      2      1      2      1      2
D  1      2      1      2      1      2",delim = " ") %>%
    mutate_all(str_trim)

To answer your question

# concatenation
result <- map2_dfc(select(data,ends_with("min")),
                   select(data,ends_with("max")),
                   function(x,y){
    str_c(x,":",y)
})


# rename columns
colnames(result) <- str_replace(colnames(result),pattern = "_.+","range")

#result
bind_cols(data[,1],result)
# A tibble: 4 x 4
  ID    O1range O2range O3range
  <chr> <chr>   <chr>   <chr>  
1 A     1:2     1:2     1:2    
2 B     1:2     1:2     1:2    
3 C     1:2     1:2     1:2    
4 D     1:2     1:2     1:2  
like image 199
yusuzech Avatar answered Mar 22 '26 04:03

yusuzech



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!