Automatic cbind column prefix and only one column

I have problems with a script that uses cbind to add columns to a data frame. I select these columns with a regex, and I like that cbind automatically provides a prefix if you add more than one column. Bit this doesn't work if you just add one column ... Even if I create this column as a data frame ...

Is there any way around this behavior?

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

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))]))) 
+7
r
source share
2 answers

The solution would be to create an intermediate data frame with log values ​​and rename the columns:

 logb = log(df[grep('^b', names(df))])) colnames(logb) = paste0('log.',names(logb)) cbind(df, logb) 
+2
source share

What about

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

Thus, you select both templates at the same time. (all three columns).
Only if only one column is selected, the columns will not match.

+2
source share

All Articles