移除千位分隔符
我导入了一个Excel文件,并得到了这样的数据框
structure(list(A = structure(1:3, .Label = c("1.100", "2.300", "5.400"), class = "factor"), B = structure(c(3L, 2L, 1L), .Label = c("1.000.000", "500", "7.800"), class = "factor"), C = structure(1:3, .Label = c("200", "3.100", "4.500"), class = "factor")), .Names = c("A", "B", "C" ), row.names = c(NA, -3L), class = "data.frame")
我现在想将这些chars
转换为numeric
或甚至integer
。 但是,点号( .
)不是小数点,而是“千位分隔符”(德语)。
我将如何正确地转换数据框?
我试过这个:
df2 <- as.data.frame(apply(df1, 2, gsub, pattern = "([0-9])\\.([0-9])", replacement= "\\1\\2")) df3 <- as.data.frame(data.matrix(df2))
然而, apply
似乎将每列转换为一系列因素。 我可以阻止这样做吗?
你可以使用这个:
sapply(df, function(v) {as.numeric(gsub("\\.","", as.character(v)))})
这使 :
ABC [1,] 1100 7800 200 [2,] 2300 500 3100 [3,] 5400 1000000 4500
这会给你一个matrix
对象,但是如果你愿意,你可以把它包装到data.frame()
。
请注意,原始数据中的列不是字符,而是因素。
编辑:或者,而不是用data.frame()
包装它,你可以直接以data.frame
获得结果:
# the as.character(.) is just in case it's loaded as a factor df[] <- lapply(df, function(x) as.numeric(gsub("\\.", "", as.character(x))))
我想我只是find了另一个解决scheme:
有必要使用stringsAsFactors = FALSE
。
喜欢这个:
df2 <- as.data.frame(apply(df1, 2, gsub, pattern = "([0-9])\\.([0-9])", replacement= "\\1\\2"), stringsAsFactors = FALSE) df3 <- as.data.frame(data.matrix(df2))