R 在不影响行名/列名的情况下转换所有列(因子为数值)

R 在不影响行名/列名的情况下转换所有列(因子为数值),r,numeric,R,Numeric,对于示例数据集,我使用以下代码将数据从因子转换为数值: sample = as.data.frame(lapply(sample, function(x) as.numeric(as.character(x)))) 要使用此代码将所有NA值替换为0: sample[is.na(sample)] = 0 但是,当我从factor转换为numeric时,列名会更改,行名会消失。为什么会发生这种情况?在将所有列转换为数字时,如何防止发生这种情况 dput(sample) structure(lis

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

sample = as.data.frame(lapply(sample, function(x) as.numeric(as.character(x))))
要使用此代码将所有NA值替换为0:

sample[is.na(sample)] = 0
但是,当我从factor转换为numeric时,列名会更改,
行名会消失。为什么会发生这种情况?在将所有列转换为数字时,如何防止发生这种情况

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.frame
check.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