我有使用连字符代替数字零的数据集,如下面的示例数据集my.data
所示。我可以将连字符替换为零,但是在将受影响的列转换为数字时遇到麻烦。我的实际数据集很大,有很多列,但我不知道哪些列将包含连字符。数据集也太大和太复杂,以至于我不愿意在将数据集读入R之前在数据集本身中使用“查找和替换”。
我认为实际数据集的前三列将是字符,其余列应为数字(如果不是连字符)。是否有一种有效且通用的方法将所有带连字符的列转换为数字,而又不知道它们是哪几列?
我在下面介绍一种方法,但是似乎很麻烦。
我在这里找到了许多类似的帖子,但它们似乎通常是在询问如何用其他内容替换缺少的观察值,或者如何将特定的已知因子列转换为字符或数字格式。我没有找到任何有关此特定问题的帖子,尽管我可能忽略了这些帖子,但其中需要转换的特定列是未知的。感谢您的任何建议。
my.data <- read.table(text = "
landuse units grade Clay Lincoln Basin McCartney Maple
apple acres AAA 1 - 3 4 6
apple acres AA 1000 900 NA NA 700
pear acres AA 10.0 20 NA 30.0 -
peach acres AAA 500 NA 350 300 200
", sep = "", header = TRUE, stringsAsFactors = FALSE, na.string=c('NA'))
my.data
str(my.data)
my.data[my.data == '-'] = '0'
as.numeric(my.data[,4:dim(my.data)[2]])
# Error: (list) object cannot be coerced to type 'double'
# The two lines below work but are too specific
# my.data$Lincoln <- as.numeric(my.data$Lincoln)
# my.data$Maple <- as.numeric(my.data$Maple)
str(my.data)
# Here I unlist the columns I want to be numeric,
# convert them to a numeric matrix and then create a data frame.
# But this seems cumbersome.
un.my.data <- unlist(my.data[,4: dim(my.data)[2]])
un.my.data <- as.numeric(un.my.data)
my.data.2 <- matrix(un.my.data, nrow=dim(my.data)[1], byrow=F)
colnames(my.data.2) <- names(my.data)[4:dim(my.data)[2]]
new.data <- data.frame(my.data[,1:3], my.data.2)
new.data
str(new.data)
最佳答案
使用正则表达式将-
替换为0
,然后转换为数字。将所有这些都包装在lapply
中:
my.data[-(1:3)] <- lapply(
my.data[-(1:3)],
function(x)as.numeric(gsub("-", 0, x))
)
my.data
landuse units grade Clay Lincoln Basin McCartney Maple
1 apple acres AAA 1 0 3 4 6
2 apple acres AA 1000 900 NA NA 700
3 pear acres AA 10 20 NA 30 0
4 peach acres AAA 500 NA 350 300 200