简体   繁体   English

从R中的数据框中删除所有字符串?

[英]Remove all strings from a data frame in R?

So I have a data frame in R that contains integers, NA's, and a random assortment of strings inside the cells. 所以我在R中有一个数据框,它包含整数,NA和单元格内随机分组的字符串。 Only one data type per cell. 每个单元只有一种数据类型。 What I'm wondering is how to change all of the cells that contain strings into NA. 我想知道的是如何将包含字符串的所有单元格更改为NA。 Any idea how I could do this? 知道我怎么能这样做吗?

If your data frame (df) is really all integers except for NAs and garbage then then the following converts it. 如果您的数据框(df)实际上是除了NAs和垃圾之外的所有整数,那么以下内容将对其进行转换。

df2 <- data.frame(lapply(df, function(x) as.numeric(as.character(x))))

You'll have a warning about NAs introduced by coercion but that's just all those non numeric character strings turning into NAs. 你会对强制引入的NAs发出警告,但只有那些非数字字符串变成了NA。

The following code also works and is more concise but runs slower. 以下代码也有效,并且更简洁但运行速度更慢。

df2 <- apply(df, 2, function(x) as.numeric(as.character(x)))

If you just want to convert selected columns then you could use a slightly more complicated command. 如果您只想转换所选列,则可以使用稍微复杂的命令。 First you need to figure out which columns you want to convert. 首先,您需要确定要转换的列。 Perhaps you save them as a logical vector of the columns you wish to change. 也许您将它们保存为您希望更改的列的逻辑向量。

df2 <- cbind(df[,!columnsToChange], apply(df[,columnsToChange], 2, function(x) as.numeric(as.character(x)))

This would knock things out of order but it would get you what you want easy enough. 这会让事情变得无序,但它可以让你轻松得到你想要的东西。

First off, if it is a data.frame , then types are the same per column. 首先,如果是data.frame ,则每列的类型相同。 So do something like class(data[,3]) to inquire about the class of third column. 所以做类似class(data[,3])来查询第三列的类。 You can then use as.numeric() et al on a given column to transform. 然后,您可以在给定列上使用as.numeric()等进行转换。 Or, per you questions, data[,3] <- NA in case you know you want to replace that column. 或者,根据您的问题, data[,3] <- NA ,以防您知道要替换该列。

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

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