0

我有一个非常大的销售数据数据框(df8)。加载时,一些我想要数字的变量加载为 chr。我想将 colname 包含单词“Order”的每一列从 chr 更改为 numeric。我怎样才能做到这一点?

4

1 回答 1

1

我会使用函数grepl来查找“订单”的出现并遍历每一列并转换为数字。请注意,变量实际上是字符,如果您的数据是一个因素(需要 ( 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
于 2015-05-04T07:56:37.560 回答