[英]How to use `stringr` in `dplyr` pipe
我在嘗試編輯dplyr
管道中的某些字符串的代碼時遇到問題。 以下是一些會引發以下錯誤的數據。 有任何想法嗎?
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 = '')
給我這個錯誤: Error in str_trunc(., string = .$name, width = 10, side = "right", ellipsis = ". . . ") : unused argument (.)
。
謝謝。
您需要mutate
或mutate_at/if/all
來更改列的內容。
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 "
我出於個人喜好使用mutate_at
。 請注意,變異列會自動作為第一個參數傳遞。 如果你想把它放在函數調用中的其他地方,請將其稱為.
。
str_trunc
沒有data
參數,因此您需要為其提供string
。 您可以使用
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 = '')
如果要添加/更新現有列,請使用mutate
函數。
你不能直接在管道中使用stringr函數。
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 "
變異(blah blah)相當於以下
> 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.