Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

automatic column prefix with cbind and just one column

Tags:

r

I have some trouble with a script which uses cbind to add columns to a data frame. I select these columns by regular expression and I love that cbind automatically provides a prefix if you add more then one column. Bit this is not working if you just append one column... Even if I cast this column as a data frame...

Is there a way to get around this behaviour?

In my example, it works fine for columns starting with a but not for b1 column.

df <- data.frame(a1=c(1,2,3),a2=c(3,4,5),b1=c(6,7,8))

cbind(df, log=log(df[grep('^a', names(df))]))

cbind(df, log=log(df[grep('^b', names(df))]))

cbind(df, log=as.data.frame(log(df[grep('^b', names(df))])))
like image 906
drmariod Avatar asked Feb 18 '15 08:02

drmariod


2 Answers

A solution would be to create an intermediate dataframe with the log values and rename the columns :

logb = log(df[grep('^b', names(df))]))
colnames(logb) = paste0('log.',names(logb))
cbind(df, logb)
like image 90
Math Avatar answered Sep 28 '22 13:09

Math


What about

cbw <- c("a","b") # columns beginning with
cbw_pattern <- paste0("^",cbw, collapse = "|")
cbind(df, log=log(df[grep(cbw_pattern, names(df))]))

This way you do select both pattern at once. (all three columns).
Only if just one column is selected the colnames wont fit.

like image 30
Rentrop Avatar answered Sep 28 '22 14:09

Rentrop