I have dataframes in a list. For each I need to combine two columns, A and B. One is numerical, the other is not. I was trying to write a function like this but it doesn't work
my_function<-function(fn){
new<-do.call(paste0, final_list1[c("Sample_ID", "Sample_ID2")])
return(new)
}
final_list2<-lapply(final_list1, my_function)
Also unite from tidy verse doesn't work.
This is an example of what I need to be done for each df in the list:
Column A | Column B | Column C | Sample_ID | Sample_ID2 |
---|---|---|---|---|
1 | 2 | 3 | abc | 123 |
result:
Column A | Column B | Column C | Sample_ID Sample_ID2 |
---|---|---|---|
1 | 2 | 3 | abc123 |
CodePudding user response:
Option using transpose
from purrr
which transposes a list of vectors to a list like this:
fn <- data.frame(A = 1,
B = 2,
C = 3,
Sample_ID = "abc",
Sample_ID2 = "123")
library(data.table)
setDT(fn)[, `Sample_ID Sample_ID2` := purrr::transpose(.("Sample_ID","Sample_ID2"))][,c("Sample_ID", "Sample_ID2"):=NULL]
fn
#> A B C Sample_ID Sample_ID2
#> 1: 1 2 3 <list[2]>
Created on 2022-07-06 by the reprex package (v2.0.1)
CodePudding user response:
myfunction<-function(fn){
new<-unite(fn, col='SampleID', c('SampleID', 'Sample_ID2'), sep='-')
return(new)
}
final_list2<-lapply(final_list1,myfunction)
Solved it