Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

dplyr

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))
like image 705
Brani Avatar asked Oct 19 '22 10:10

Brani


1 Answers

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,.)))
like image 123
nicola Avatar answered Oct 22 '22 02:10

nicola