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))
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,.)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With