是否存在使用dplyr
在数据框中取消列出或取消嵌套向量的函数或方式?我有以下示例。
library(tidyverse)
df <- tibble(x =
c("c(\"Police\", \"Pensions\")",
"c(\"potato\", \"sweetpotato\")"))
df
# A tibble: 2 x 1
x
<chr>
1 "c(\"Police\", \"Pensions\")"
2 "c(\"potato\", \"sweetpotato\")"
我想将dataframe列转换成这样的格式。
> df
# A tibble: 4 x 1
x
<chr>
1 Police
2 Pensions
3 Potato
4 Sweetpotato
答案 0 :(得分:3)
一个选项是separate_rows
library(tidyverse)
df %>%
separate_rows(x) %>%
filter(!x %in% c('c', ''))
# A tibble: 4 x 1
# x
# <chr>
#1 Police
#2 Pensions
#3 potato
#4 sweetpotato
注意:分离和filter
或者另一种选择是提取引号之间的单词,然后提取unnest
df %>%
mutate(x = str_extract_all(x, '(?<=")[A-Za-z]+')) %>%
unnest
# A tibble: 4 x 1
# x
# <chr>
#1 Police
#2 Pensions
#3 potato
#4 sweetpotato
在更大的数据上,
df1 <- df[rep(1:nrow(df), each = 1e5), ]
system.time({
df1 %>%
separate_rows(x) %>%
filter(!x %in% c('c', ''))
})
#. user system elapsed
# 0.916 0.033 0.939
system.time({
df1 %>%
mutate(x = str_extract_all(x, '(?<=")[A-Za-z]+')) %>%
unnest
})
# user system elapsed
# 0.763 0.015 0.773
system.time({
df1 %>%
mutate(x = map(x,~eval(parse(text=.)))) %>%
unnest
})
#user system elapsed
# 15.643 1.813 17.375
答案 1 :(得分:2)
由于R代码存储在字符串中,因此我认为使用eval(parse(text= your_input))
是很自然的。
在其上使用unnest
会得到:
df %>%
mutate(x = map(x,~eval(parse(text=.)))) %>%
unnest
# A tibble: 4 x 1
# x
# <chr>
# 1 Police
# 2 Pensions
# 3 potato
# 4 sweetpotato