tsgsteele
tsgsteele

Reputation: 97

No applicable method for 'separate_' applied to an object of class "character"

I have four dataframes in my environment, each with a first column that looks like this:

      product.consom.unit.tax.currency.geo.time
1                 6000,4161901,KWH,I_TAX,EUR,AL
2                 6000,4161901,KWH,I_TAX,EUR,AT
3                 6000,4161901,KWH,I_TAX,EUR,BA
4                 6000,4161901,KWH,I_TAX,EUR,BE
5                 6000,4161901,KWH,I_TAX,EUR,BG
6                 6000,4161901,KWH,I_TAX,EUR,CY

I want separate the first column into multiple columns using the tidyr separate:

data <- list(c("df1", "df2", "df3", "df4"))
sep <- function(x){
  x <- separate(x, 1, c("prod", "band", "unit", "tax", "currency", "geo"), ",", remove = TRUE)
}
lapply(data, sep)

When I run the lapply i get the following error:

Error in UseMethod("separate_") : no applicable method for 'separate_' applied to an object of class "character"

Any and all help would be much appreciated!

Upvotes: 3

Views: 12715

Answers (2)

Darren Tsai
Darren Tsai

Reputation: 35554

The comments under your post have pointed out the problem. I provide a solution combining lapply() and list2env() to achieve what you want:

library(tidyr)
data <- list(df1, df2, df3, df4)
names(data) <- paste0("df", 1:4)
list2env(lapply(data, separate, 1, c("prod", "band", "unit", "tax", "currency", "geo"), ","), .GlobalEnv)

(The argument remove in separate() defaults to TRUE, so I ignore it.)

df1 to df4 in the workspace will be overwritten to the separated forms.

Upvotes: 1

Zhiqiang Wang
Zhiqiang Wang

Reputation: 6759

Your code actually works once on my machine once I changed the data <- list(c("df1", "df2", "df3", "df4")) into data <- list(df1, df2, df3, df4) as suggested by @gersht and @NelsonGon. You need to remove c() as well.

I have also tried a for loop approach:


df1 <- data.frame(product.consom.unit.tax.currency.geo.time = c( 
            "6000,4161901,KWH,I_TAX,EUR,AL",
           "6000,4161901,KWH,I_TAX,EUR,AT",
             "6000,4161901,KWH,I_TAX,EUR,BA",
             "6000,4161901,KWH,I_TAX,EUR,BE",
             "6000,4161901,KWH,I_TAX,EUR,BG",
             "6000,4161901,KWH,I_TAX,EUR,CY"))
df2 <- df3 <- df4 <- df1
data <- list(df1, df2, df3, df4)

library(tidyr)
for (i in 1:4) {
  assign(paste0("df", i), separate(data.frame(data[i]), 1, c("prod", "band", "unit", "tax", "currency", "geo"), ",", remove = TRUE)) 
}              

Upvotes: 1

Related Questions