gpt4 book ai didi

r - 在不影响行名/列名的情况下转换所有列(因子到数字)

转载 作者:行者123 更新时间:2023-12-02 08:22:21 24 4
gpt4 key购买 nike

对于我的示例数据集,我使用以下代码将数据从因子转换为数值:

sample = as.data.frame(lapply(sample, function(x) as.numeric(as.character(x))))

为了然后使用此代码将所有 NA 值替换为 0:

sample[is.na(sample)] = 0

但是,当我从因子转换为数字时,列名会发生变化,并且 rownames 会消失。为什么会发生这种情况,在将所有列转换为数字时如何防止它发生?

dput(sample)
structure(list(`2015-10-08 00:05:00` = structure(c(NA, NA, NA,
NA, 2L, NA), .Names = c("72", "79", "82", "83", "116", "120"), .Label = c(" 1",
" 2", " 3", " 5", "2015-10-08 00:05:00"), class = "factor"),
`2015-10-08 00:12:00` = structure(c(NA, 1L, NA, NA, NA, NA
), .Names = c("72", "79", "82", "83", "116", "120"), .Label = c(" 1",
" 2", " 3", "2015-10-08 00:12:00"), class = "factor"), `2015-10-08 00:34:00` = structure(c(NA,
NA, NA, NA, 1L, NA), .Names = c("72", "79", "82", "83", "116",
"120"), .Label = c(" 1", " 2", " 3", " 4", "2015-10-08 00:34:00"
), class = "factor"), `2015-10-08 00:40:00` = structure(c(NA_integer_,
NA_integer_, NA_integer_, NA_integer_, NA_integer_, NA_integer_
), .Names = c("72", "79", "82", "83", "116", "120"), .Label = c(" 1",
" 2", "2015-10-08 00:40:00"), class = "factor"), `2015-10-08 01:32:00` = structure(c(NA,
NA, 1L, 1L, 3L, NA), .Names = c("72", "79", "82", "83", "116",
"120"), .Label = c(" 1", " 2", " 3", " 4", " 6", " 8", "2015-10-08 01:32:00"
), class = "factor"), `2015-10-08 01:52:00` = structure(c(1L,
NA, NA, NA, NA, NA), .Names = c("72", "79", "82", "83", "116",
"120"), .Label = c(" 1", " 2", " 3", "2015-10-08 01:52:00"
), class = "factor")), .Names = c("2015-10-08 00:05:00",
"2015-10-08 00:12:00", "2015-10-08 00:34:00", "2015-10-08 00:40:00",
"2015-10-08 01:32:00", "2015-10-08 01:52:00"), row.names = c("72",
"79", "82", "83", "116", "120"), class = "data.frame")

最佳答案

您可以使用 data.frame 代替 as.data.framecheck.names=F 告诉函数保留列名。使用 row.names 继承行名。

顺便说一句,尽量不要在R中使用sample作为变量名,因为它是R的保留字。

d1 = data.frame(lapply(d1, function(x) as.numeric(as.character(x))),
check.names=F, row.names = rownames(d1))
d1[is.na(d1)] = 0

关于r - 在不影响行名/列名的情况下转换所有列(因子到数字),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35881107/

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