I need to be able to apply the following function to the all of the columns in the data frame:
data2$Zones <- vapply(data2$Zones, paste, collapse = ", ", character(1L))
how can I do this?
I need to be able to apply the following function to the all of the columns in the data frame:
data2$Zones <- vapply(data2$Zones, paste, collapse = ", ", character(1L))
how can I do this?
Based on your description:
data2[] <- lapply(data2, function(x) vapply(x, paste, collapse = ", ", character(1L)))
Or
data2[] <- lapply(data2, function(x) vapply(x, toString, character(1L)))
I would do using data.table
Here is an example code:
library(data.table)
setDT(data2)
collist <- c("col1", "col2", "col3") # whatever columns you have in data2
newcols <- c("col1new", "col2new", "col3new") # the new columns
data2[, (newcols) := lapply(.SD, function(x) paste(x, collapse = ", "), .SDcols = collist]
In case you want to apply the function on some columns, e.g., paste some columns and create a new column:
data2[, newColumn := paste(col1, col2, col3, collapse = ", ")]
Are you trying to add a ", 1" to each cell in each column?
library(purrr)
df <- tibble(x = c("a", "b"),
y = c("c", "d"),
z = c("e", "f"))
df
# A tibble: 2 x 3
# x y z
# <chr> <chr> <chr>
# 1 a c e
# 2 b d f
df2 <- map_dfc(df, ~ paste(.x, sep = ", ", character = 1L))
df2
# A tibble: 2 x 3
# x y z
# <chr> <chr> <chr>
# 1 a, 1 c, 1 e, 1
# 2 b, 1 d, 1 f, 1