I have a dataframe df, which has a chr column Col1, that looks like this:
| Col1 |
|---|
| "apple;orange;pear" |
| "orange;apple" |
I want to create a new column, in which I count the number of words in Col1. I did this previously with this code:
df$Count <- sapply(df$Col1, function(x) {
sum(str_count(x, ";")+1)
})
It worked well until now.
I’ve recently updated the rlang package to version 1.0.6 and after updating I’m constantly getting this error:
Error in
stop_vctrs():
! Input must be a vector, not an environment.
Runrlang::last_error()to see where the error occurred.
I ran rlang::last_error() :
Backtrace:
- base::sapply(…)
- vctrs:::stop_scalar_type(
<fn>(<env>), "")- vctrs:::stop_vctrs(msg, "vctrs_error_scalar_type", actual = x)
Runrlang::last_trace()to see the full context.
I also did a simple test vector with c() and tried using str_count() with this, but it gives the same error.
>Solution :
A base R approach to count the number of words separated by a ";" is:
lengths(gregexpr(";", df$Col1)) + 1
# [1] 3 2
To create a new column, simply:
df$NewCol <- lengths(gregexpr(";", df$Col1)) + 1
# Col1 NewCol
# 1 apple;orange;pear 3
# 2 orange;apple 2
Data
df <- data.frame(Col1 = c("apple;orange;pear","orange;apple"))