Reputation: 1944
I am having trouble with this code which attempts to edit some strings in a dplyr
pipe. Here is some data that throws the following error. Any ideas?
data_frame(id = 1:5,
name = c('this and it pretty long is a',
'name is a',
'so and so and so and so and so',
'this is a',
'this is a variabel name'))
%>%
str_trunc(.,
string = .$name,
width = 10,
side='right',
ellipsis = '')
Gives me this error: Error in str_trunc(., string = .$name, width = 10, side = "right", ellipsis = ". . . ") : unused argument (.)
.
Thanks.
Upvotes: 6
Views: 7029
Reputation: 1659
You need to mutate
or mutate_at/if/all
to change the contents of the column.
data_frame(id = 1:5,
name = c('this and it pretty long is a',
'name is a',
'so and so and so and so and so',
'this is a',
'this is a variabel name')) %>%
mutate_at("name", str_trunc, width = 10, side='right', ellipsis = '')
# A tibble: 5 x 2
id name
<int> <chr>
1 1 this and i
2 2 name is a
3 3 "so and so "
4 4 this is a
5 5 "this is a "
I use mutate_at
here out of personal preference. Note that the mutating column is automatically passed as the first argument. If you want to put it somewhere else in the function call, refer to it as .
.
Upvotes: 9
Reputation: 153
if you want to add/update column from existing one, please use mutate
function.
you can't use the stringr function directly in the pipe.
data_frame(id = 1:5,
name = c('this and it pretty long is a',
'name is a',
'so and so and so and so and so',
'this is a',
'this is a variabel name')) %>%
mutate(name=str_trunc(name,width=10,side='right',ellipsis=''))
## # A tibble: 5 x 2
## id name
## <int> <chr>
## 1 1 this and i
## 2 2 name is a
## 3 3 "so and so "
## 4 4 this is a
## 5 5 "this is a "
the mutate(blah blah) is equivalent to followings
> df<-data_frame(id = 1:5,
name = c('this and it pretty long is a',
'name is a',
'so and so and so and so and so',
'this is a',
'this is a variabel name'))
> df
## # A tibble: 5 x 2
## id name
## <int> <chr>
## 1 1 this and it pretty long is a
## 2 2 name is a
## 3 3 so and so and so and so and so
## 4 4 this is a
## 5 5 this is a variabel name
> df$name<-str_trunc(df$name,width=10,side='right',ellipsis='')
> df
## # A tibble: 5 x 2
## id name
## <int> <chr>
## 1 1 this and i
## 2 2 name is a
## 3 3 "so and so "
## 4 4 this is a
## 5 5 "this is a
Upvotes: 0
Reputation: 541
There is no data
parameter in str_trunc
, so you need to feed it the string
. You can use
data_frame(id = 1:5,
name = c('this and it pretty long is a',
'name is a',
'so and so and so and so and so',
'this is a',
'this is a variabel name'))$name %>%
str_trunc(width = 10,
side='right',
ellipsis = '')
Upvotes: 0