Brani
Brani

Reputation: 6784

dplyr: Create a new variable as a function of all existing variables without defining their names

In the following dataframe I want to create a new variable as the following function of all existing ones:

as.numeric(paste0(df[i,],collapse=""))

However, I don't want to define the column names explicitly because their number and names maybe different each time. How can I do that using dplyr?

The equivalent in base r would be something like this:

apply(df,1,function(x) as.numeric(paste0(x,collapse="")))


df <- structure(list(X1 = c(50, 2, 2, 50, 5, 5, 2, 50, 5, 5, 50, 2, 
5, 5, 50, 2, 2, 50, 9, 9, 9, 9, 9, 9), X2 = c(2, 50, 5, 5, 50, 
2, 5, 5, 50, 2, 2, 50, 9, 9, 9, 9, 9, 9, 50, 2, 2, 50, 5, 5), 
    X3 = c(5, 5, 50, 2, 2, 50, 9, 9, 9, 9, 9, 9, 50, 2, 2, 50, 
    5, 5, 2, 50, 5, 5, 50, 2), X4 = c(9, 9, 9, 9, 9, 9, 50, 2, 
    2, 50, 5, 5, 2, 50, 5, 5, 50, 2, 5, 5, 50, 2, 2, 50)), class = "data.frame", .Names = c("X1", 
"X2", "X3", "X4"), row.names = c(NA, -24L))

Upvotes: 5

Views: 861

Answers (1)

nicola
nicola

Reputation: 24520

You can try:

df %>% mutate(newcol=as.numeric(do.call(paste0,df)))

Or (as you suggested, maybe more dplyr style):

df %>% mutate(newcol=as.numeric(do.call(paste0,.)))

Upvotes: 3

Related Questions