简体   繁体   English

如何将 dataframe 中的所有数字字符串转换为 R 中的数字?

[英]How do you convert all numeric strings in a dataframe to numeric in R?

I'm pretty new to R and I have a large dataframe that I have read from a file.我对 R 很陌生,我有一个大的 dataframe ,我从文件中读取。 The data inside has columns with data that are both "normal" strings like "Iceland" but it also has columns that have numerics but as strings, like "25.1".里面的数据列的数据都是“普通”字符串,如“Iceland”,但也有列有数字但为字符串,如“25.1”。 Is there a way to convert all strings that are of only numbers to numerics?有没有办法将所有只有数字的字符串转换为数字?

I know how to do it for one column: var <- as.numeric(dataFrame$var) but this isn't very effective as my data frame has about 160 columns.我知道如何为一列执行此操作: var <- as.numeric(dataFrame$var)但这不是很有效,因为我的数据框有大约 160 列。

I've tried to convert the entire dataframe as follows, but it doesn't work:我尝试将整个 dataframe 转换如下,但它不起作用:

DF2 <- lapply(DF1, function(x) {
  ifelse(!is.na(suppressWarnings(as.numeric(x))), as.numeric(as.character(x)), x)
})

Testing a column with DF2$colName returns "character", not "numeric".使用DF2$colName测试列会返回“字符”,而不是“数字”。 This also seems to turn the dataframe into a list.这似乎也将 dataframe 变成了一个列表。

As a side note, I've read in the dataframe using read.csv() without any arguments except for the filename.作为旁注,我已经阅读了 dataframe 使用read.csv()除了文件名之外没有任何 arguments 。 Additionally, the columns don't mix types, it's either all normal strings or all numeric strings.此外,这些列不混合类型,它要么都是普通字符串,要么都是数字字符串。

Thank you!谢谢!

we can use the type.convert function我们可以使用type.convert function

example data示例数据

df <- data.frame(a=c("2.1"), b='iceland')

check classes in original example data:检查原始示例数据中的类:

df |> lapply(\(x) class(x))

$a
[1] "character"

$b
[1] "character"

Transformation转型

df <- type.convert(df, as.is =TRUE)

testing output测试 output

df |> lapply(\(x) class(x))

$a
[1] "numeric"

$b
[1] "character"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM