Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

str_replace_all not working in pipeline

Here's my code:

df <- df %>%
  filter(conditions x, y, and z) %>%
  str_replace_all(string, pattern, replacement)

When doing this, I got the error:

Error in str_replace_all(., string, pattern, replacement) :
  unused argument("")

I know the code is not at all useful in terms of replication, as I've said before, I can't share the data, but assume the input was correct (I have since gotten it to work by mutating the variable instead). The replacement was an empty string, but that ought not to matter as far as I know.

I'm just curious why str_replace_all does not work in a pipeline, anyone have any insight?

like image 369
MokeEire Avatar asked Aug 24 '17 22:08

MokeEire


1 Answers

Edit: It appears @akrun has deleted his answer, so it is reproduced below. I made the (perhaps faulty) assumption you wished to transform the whole dataframe, and that the dataframe was appropriately formatted. These issues are avoided with clearer questions, and sample data.

It's a little hard to tell with no clue as to the values of your global variables and no data (you can generate fake data, btw, as long as it presents the same issue), but my guess is below.

When piping, the previous result is piped in as the first argument of the next function. You can see this in the error message: Error in str_replace_all(., string, pattern, replacement) -- the ., shows the piped in argument. Here, the first argument is "string". Therefore, the piped in result is being used as string, "string" is used as pattern, "pattern" is being used for replacement, and the "" you put in for replacement is left as an unused argument, causing your error.

Might help to use str_replace_all(pattern, replacement), or specify arguments: str_replace_all(pattern = pattern, replacement = replacement)

Ex.

data <- as.data.frame(matrix(ncol=2, nrow=2))
data$V1 <- c("  NA", "foo")
data$V2 <- c("bar", "boo")
data %>%
    str_replace_all("oo", "xx")

If you only wish to transform one column (from @akrun): Simply use mutate to create a new column based off of the preexisting column. If you wish to replace the column, give it the same name:

Ex.

data <- as.data.frame(matrix(ncol=2, nrow=2))
data$V1 <- c("  NA", "foo")
data$V2 <- c("bar", "boo")
data
    V1  V2
1   NA bar
2  foo boo

#new column
data %>%
    mutate(new = str_replace_all(V1, "oo", "xx"))

    V1  V2  new
1   NA bar   NA
2  foo boo  fxx

#column replacement
data %>%
    mutate(V1 = str_replace_all(V1, "oo", "xx"))

    V1  V2
1   NA bar
2  fxx boo
like image 111
aku Avatar answered Sep 28 '22 06:09

aku