I'm trying to pass a tibble to a function call and then perform some dplyr transformations on it. However, when I pass the tibble to the function it tells me that I cannot perform mutate
on an object of class character.
For example, say I have this data and this code:
dataframe_1 <- tibble(var1 = c('a','b','c','d'), var2 = c('e','f','g','h'))
dataframe_2 <- tibble(var1 = c(1,2,3,4), var2 = c(5,6,7,8))
dataframe_3 <- tibble(var1 = c('i','j','k','l'), var2 = c('m','n','o','p'))
dataframe_4 <- tibble(var1 = c(9,10,11,12), var2 = c(13,14,15,16))
function_name <- function(.x) {
.x %>%
mutate(var3 = .x)
}
print_table <- map_dfr(
.x = dataframe_1,
.f = function_name
)
I get the error Error in UseMethod("mutate") : no applicable method for 'mutate' applied to an object of class "character"
.
But if I run this:
function_name <- function(.x) {
return(.x)
}
print_table <- map_dfr(
.x = dataframe_1,
.f = function_name
)
I get
print_table
# A tibble: 4 × 2
var1 var2
<chr> <chr>
1 a e
2 b f
3 c g
4 d h
So R is able to tell that dataframe_1
is in fact a tibble, and I know that it's possible to pipe tibbles into a mutate()
command.
Can anyone see where i'm going wrong here?
CodePudding user response:
If we are creating the object name as a column, get all the objects (mget
) into a named list
based on the pattern
in the object names created in ls
, then loop over the list
with imap
, and create the column from the names using .y
library(dplyr)
library(purrr)
mget(ls(pattern = 'dataframe_\\d ')) %>%
imap(~ .x %>%
mutate(var3 = .y))