根据colnames中的子字符串更改coltypes

时间:2015-05-04 07:49:32

标签: r dataframe read.csv column-types

我有一个非常大的销售数据数据框(df8)。加载时,我希望将一些变量数字加载为chr。我想更改colname包含单词" Order"从chr到数字。我怎么能这样做?

1 个答案:

答案 0 :(得分:1)

我会使用函数grepl来查找“order”的出现并浏览每一列并转换为numeric。请注意,变量实际上是字符,如果您的数据是一个因素(需要(as.numeric(as.character(x))),它将无法工作。

# create data.frame with characters
xy <- data.frame(a = runif(5), b.order = runif(5), cOrder = runif(5))
xy[, c(2, 3)] <- sapply(xy[, c(2, 3)], FUN = as.character)
str(xy)
'data.frame':   5 obs. of  3 variables:
 $ a      : num  0.914 0.468 0.106 0.624 0.841
 $ b.order: chr  "0.363523897947744" "0.56488766730763" "0.42081760126166" "0.560672372812405" ...
 $ cOrder : chr  "0.949268750846386" "0.596737345447764" "0.368769273394719" "0.717566329054534" ...

with.order <- grepl("order", names(xy), ignore.case = TRUE)

xy[, with.order] <- sapply(xy[, with.order], FUN = as.numeric)
str(xy)
'data.frame':   5 obs. of  3 variables:
 $ a      : num  0.914 0.468 0.106 0.624 0.841
 $ b.order: num  0.364 0.565 0.421 0.561 0.768
 $ cOrder : num  0.949 0.597 0.369 0.718 0.417