如何将文本货币列替换为数字 R data.table

How to Replace Text Currency Columns As Numeric R data.table

如何将许多列转换为数字,因为它们包含 '$'

library(data.table)
dt = data.table( text = c('a', 'b', 'c'), price = c('1.1', 2.2, 3.3), other = c('','','') )

我认为以下方法可能有效:

dt[ , names(dt) := as.list( gsub('\$', '', dt) ) ]
dt = type.convert( dt , as.is = TRUE )

但是,它没有。

我收到以下错误:

Warning messages:
1: In `[.data.table`(dt, , `:=`(names(dt), as.list(gsub("\$", "",  :
  Coercing 'character' RHS to 'double' to match the type of the target column (column 2 named 'price').
2: In `[.data.table`(dt, , `:=`(names(dt), as.list(gsub("\$", "",  :
  NAs introduced by coercion

你能帮忙吗?

使用lapply-

library(data.table)

cols <- names(dt)
#Or for selected columns.
#cols <- c('other', 'price')
dt[ , (cols) := lapply(.SD, function(x) gsub('\$', '', x)), .SDcols = cols]
dt = type.convert( dt , as.is = TRUE )
dt

#   text price other
#1:    a   1.1     1
#2:    b   2.2     2
#3:    c   3.3     3