LDT
LDT

Reputation: 3088

separate a column by a string [special case where the string is not always present]

I have a data frame that looks like this

col1 <- c("test-1", "test-2","test")
col2 <- c(1,2,3)
df <- data.frame(col1,col2)

I would to like separate col1 and my data look like this

check1 check2 col2 
test      1    1
test      2    2 
test     NA    3

a function like this would not work

separate(df, col1, c("check1,check2"),"-")

any idea why?

Upvotes: 0

Views: 29

Answers (2)

akrun
akrun

Reputation: 887118

Regarding the OP's issue, instead of creating a vector of column names, there is a syntax issue i.e. c("check1,check2") is a single element and it should be c("check1","check2")

separate(df, col1, c("check1","check2"),"-")

Upvotes: 2

AnilGoyal
AnilGoyal

Reputation: 26218

use fill = 'right' to fill NAs in case of missing values and prevent displaying any warnings

col1 <- c("test-1", "test-2","test")
col2 <- c(1,2,3)
df <- data.frame(col1,col2)
library(tidyverse)
df %>% separate(col1, into = c('checkA', 'checkB'), sep = '-', fill = 'right')
#>   checkA checkB col2
#> 1   test      1    1
#> 2   test      2    2
#> 3   test   <NA>    3

Created on 2021-06-01 by the reprex package (v2.0.0)

Upvotes: 2

Related Questions