df <- data.frame(x = c(NA, "a.b", "a.d", "b.c"))
df %>%
{if (is_html_output()) print_table(.) else .}
x |
---|
NA |
a.b |
a.d |
b.c |
A | B |
---|---|
NA | NA |
a | b |
a | d |
b | c |
If you just want the second variable:
B |
---|
NA |
b |
d |
c |
If every row doesn’t split into the same number of pieces, use the extra and fill arguments to control what happens
#
df <- data.frame(x = c("a", "a b", "a b c", NA))
df %>%
separate(x, c("a", "b")) %>%
{if (is_html_output()) print_table(.) else .}
a | b |
---|---|
a | NA |
a | b |
a | b |
NA | NA |
The same behaviour drops the c but no warnings
df %>%
separate(x, c("a", "b"), extra = "drop", fill = "right") %>%
{if (is_html_output()) print_table(.) else .}
a | b |
---|---|
a | NA |
a | b |
a | b |
NA | NA |
df %>%
separate(x, c("a", "b"), extra = "merge", fill = "left") %>%
{if (is_html_output()) print_table(.) else .}
a | b |
---|---|
NA | a |
a | b |
a | b c |
NA | NA |
a | b | c |
---|---|---|
a | NA | NA |
a | b | NA |
a | b | c |
NA | NA | NA |
df <- data.frame(x = c("x: 123", "y: error: 7"))
df %>%
separate(x, c("key", "value"), ": ", extra = "merge") %>%
{if (is_html_output()) print_table(.) else .}
key | value |
---|---|
x | 123 |
y | error: 7 |
df <- data.frame(x = c(NA, "a?b", "a.d", "b:c"))
df %>%
separate(x, c("A","B"), sep = "([\\.\\?\\:])") %>%
{if (is_html_output()) print_table(.) else .}
A | B |
---|---|
NA | NA |
a | b |
a | d |
b | c |
df <- data.frame(x = c("a:1", "a:2", "c:4", "d", NA))
df %>%
separate(x, c("key","value"), ":") %>%
str
# 'data.frame': 5 obs. of 2 variables:
# $ key : chr "a" "a" "c" "d" ...
# $ value: chr "1" "2" "4" NA ...
# 'data.frame': 5 obs. of 2 variables:
# $ key : chr "a" "a" "c" "d" ...
# $ value: int 1 2 4 NA NA
Argument col can take quasiquotation to work with strings
var <- "x"
df %>%
separate(!!var, c("key","value"), ":") %>%
{if (is_html_output()) print_table(.) else .}
key | value |
---|---|
a | 1 |
a | 2 |
c | 4 |
d | NA |
NA | NA |