automatic column prefix with cbind and just one column

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))])))

解决办法是用日志值创建一个中间数据框并重命名列:

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

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.

链接地址: http://www.djcxy.com/p/83752.html

上一篇: 为什么中断异常检查异常?

下一篇: 带有cbind的自动列前缀和只有一列