如何将空格的字符串胁到数字向量的一列?
这似乎很简单,但是我尝试过的任何方法都没有起作用。
我有一个带有以下结构的tibble b2d
:
A tibble: 5 × 2
bin day
<chr> <chr>
1 Bin_1 2 5 6 7 8 9 10 11 12 13 14 15 19 21 26 27 28 29 30
2 Bin_2 1 2 4 6 13 14 15 16 17 18 20 21 22 23 24 25 26 27 28 29 30 31
3 Bin_3 2 3 4 5 7 8 13 14 18 26
4 Bin_4 19
5 Bin_5 1 8 20
day
是由整数和空格组成的字符串列。我想将每个字符串转换为一个数字向量,以便可以使用%
in% operator搜索day
( eg 1 %in%b2d $ DAY [[1]
返回false
; 25%in%b2d $ day [[2]]
返回true < /代码>)。
我所需的输出:
A tibble: 5 × 2
bin day
<chr> <list>
1 Bin_1 <num [19]>
2 Bin_2 <num [22]>
3 Bin_3 <num [10]>
4 Bin_4 <num [1]>
5 Bin_5 <num [3]>
我尝试了什么,没有运气:
https://stackoverflow.com/a/4445211660/7976890
b2d %>% mutate(day = as.numeric(unlist(strsplit(day, " "))))
https://stackoverflow.com/a/a/26342774/7976890
b2d %>% mutate(day = as.numeric(strsplit(day, split = " ", fixed = TRUE)[[1]]))
This seems simple, but none of the approaches I've tried have worked.
I have a tibble b2d
with the following structure:
A tibble: 5 × 2
bin day
<chr> <chr>
1 Bin_1 2 5 6 7 8 9 10 11 12 13 14 15 19 21 26 27 28 29 30
2 Bin_2 1 2 4 6 13 14 15 16 17 18 20 21 22 23 24 25 26 27 28 29 30 31
3 Bin_3 2 3 4 5 7 8 13 14 18 26
4 Bin_4 19
5 Bin_5 1 8 20
day
is a column of character strings comprised of integers and spaces. I want to convert each string to a numeric vector, such that day
can be searched with the %in%
operator (e.g. 1 %in% b2d$day[[1]]
returns FALSE
; 25 %in% b2d$day[[2]]
returns TRUE
).
My desired output:
A tibble: 5 × 2
bin day
<chr> <list>
1 Bin_1 <num [19]>
2 Bin_2 <num [22]>
3 Bin_3 <num [10]>
4 Bin_4 <num [1]>
5 Bin_5 <num [3]>
What I've tried, without luck:
https://stackoverflow.com/a/44521160/7976890
b2d %>% mutate(day = as.numeric(unlist(strsplit(day, " "))))
https://stackoverflow.com/a/26342774/7976890
b2d %>% mutate(day = as.numeric(strsplit(day, split = " ", fixed = TRUE)[[1]]))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当它被
unlist
编辑时,它将取消整个列表。我们可能需要使用map
循环列表并转换为numeric
。map
返回一个列表
When it is
unlist
ed, it will unlist the whole list. We may need to loop over the list withmap
and convert tonumeric
.map
returns alist