Reputation: 53826
I'm attempting to create a single columned tibble where each row is single word from a vector but I'm unsure how to add a column name as the tibble has not been created.
This code :
as_tibble(strsplit("this is a test" , " "))
returns error :
Error: Column 1 must be named
How to name Column 1 ?
I attempted to add a name to result of
strsplit("this is a test" , " ")
but this is a string and so cannot be named ?
[[1]] [1] "this" "is" "a" "test"
Upvotes: 1
Views: 2438
Reputation: 796
You could just do:
> strsplit("this is a test" , " ") %>% as_tibble(validate=F)
# A tibble: 4 x 1
``
<chr>
1 this
2 is
3 a
4 test
or you could do sth like:
> strsplit("this is a test" , " ") %>% map(as_tibble) %>% bind_rows
# A tibble: 4 x 1
value
<chr>
1 this
2 is
3 a
4 test
This is useful because you sometimes need a default column name in order to do more complex list operations
Upvotes: 1
Reputation: 305
I would transform the strsplit to a list, if you wanted a column name x:
as_tibble(list(x = (strsplit("this is a test" , " "))[[1]]))
# A tibble: 4 x 1
x
<chr>
1 this
2 is
3 a
4 test
Upvotes: 1
Reputation: 1233
Isolate the first element of the list created:
as_tibble(strsplit("this is a test" , " ")[[1]])
Or name your list elements:
ls=strsplit("this is a test" , " ")
names(ls)="test_tibble"
as_tibble(ls)
Upvotes: 1