Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Error while using str_count() function in R: 'Input must be a vector, not an environment.'

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Error in stop_vctrs():
! Input must be a vector, not an environment.
Run rlang::last_error() to see where the error occurred.

I ran rlang::last_error() :

Backtrace:

  1. base::sapply(…)
  2. vctrs:::stop_scalar_type(<fn>(<env>), "")
  3. vctrs:::stop_vctrs(msg, "vctrs_error_scalar_type", actual = x)
    Run rlang::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"))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading