gpt4 book ai didi

r - 将数据框中的连字符转换为零,然后将受影响的列转换为 R 中的数字

转载 作者:行者123 更新时间:2023-12-03 22:32:35 24 4
gpt4 key购买 nike

我有一个数据集,其中使用连字符代替数字零,如下面的示例数据集 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

关于r - 将数据框中的连字符转换为零,然后将受影响的列转换为 R 中的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13470593/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com