Home > Blockchain >  Split a column in two: dataframes within a list
Split a column in two: dataframes within a list

Time:04-05

I have a list with a large number of dataframes, all the dataframes have the same columns. I need to split one column into two.

Here is a working example:

myList <- list(A = data.frame(ID = c("A:234", "A:345"), 
                          Test = c(1, 1), 
                          Value = 1:2), 
           B = data.frame(ID = c("B:5565", "B:2415", "B:65684"), 
                          Test = c(1, 3, 5), 
                          Value = 1:3))

Here is what I would like to get:

myList <- list(A = data.frame(ch = c("A", "A"),
                          pos = c(234,345),
                          Test = c(1, 1), 
                          Value = 1:2), 
           B = data.frame(ch = c("B", "B", "B"),
                          pos=c(5565,2415,65684),
                          Test = c(1, 3, 5), 
                          Value = 1:3))

I have traid to use splitstackshape::cSplit with lappy, but without success.

CodePudding user response:

lapply(myList, tidyr::separate, col = "ID", into = c("ch", "pos"), sep = ":")
# $A
#   ch pos Test Value
# 1  A 234    1     1
# 2  A 345    1     2
# 
# $B
#   ch   pos Test Value
# 1  B  5565    1     1
# 2  B  2415    3     2
# 3  B 65684    5     3

CodePudding user response:

A base R option using read.table

lapply(
    myList,
    function(x) {
        with(
            x,
            cbind(
                setNames(read.table(text = ID, sep = ":"), c("ch", "pos")),
                x[setdiff(names(x),"ID")]
            )
        )
    }
)

gives

$A
  ch pos Test Value
1  A 234    1     1
2  A 345    1     2

$B
  ch   pos Test Value
1  B  5565    1     1
2  B  2415    3     2
3  B 65684    5     3

CodePudding user response:

Here is pipe version using map:

library(tidyverse)
myList %>%
  map(~separate(., ID, c("ch", "pos"), sep = ":"))
$A
  ch pos Test Value
1  A 234    1     1
2  A 345    1     2

$B
  ch   pos Test Value
1  B  5565    1     1
2  B  2415    3     2
3  B 65684    5     3
  • Related