I would like to rename some columns within a dplyr
chain after casting. However, I don't know how to call the names of the current structure within the rename.vars
function.
I have this data.frame:
library(gdata)
library(dplyr)
library(reshape2)
dat <- structure(list(user = c(1101L, 1102L, 1103L, 1104L, 1105L, 1101L,
1102L, 1103L, 1104L, 1105L, 1101L, 1102L, 1103L, 1104L, 1105L,
1101L, 1102L, 1103L, 1104L, 1105L), campaign = structure(c(1L,
2L, 1L, 2L, 3L, 3L, 4L, 5L, 2L, 1L, 1L, 3L, 3L, 2L, 3L, 2L, 1L,
4L, 3L, 2L), .Label = c("A", "B", "C", "D", "E"), class = "factor"),
impression_number = c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L,
2L, 3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L)), .Names = c("user",
"campaign", "impression_number"), class = "data.frame", row.names = c(NA,
-20L))
which looks like this:
user campaign impression_number
1 1101 A 1
2 1102 B 1
3 1103 A 1
4 1104 B 1
5 1105 C 1
6 1101 C 2
When I try to run the following command, it errors because I am not referencing the names of the current object:
dat %>%
dcast(user ~ impression_number, value.var = 'campaign') %>%
rename.vars(names(.)[2:5], paste0('impression_', names(.)[2:5]))
Ideally, I want this data frame:
user impression_1 impression_2 impression_3 impression_4
1 1101 A C A B
2 1102 B D C A
3 1103 A E C D
4 1104 B B B C
5 1105 C A C B
What can I do to refer to the names of the current object? I've also tried lhs
from the documentation, but that's just a placeholder and didn't work either.
Thanks in advance!