简体   繁体   English

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

[英]converting all columns (factor to numeric) without affecting rownames/colnames

For my sample dataset, I use the following code to convert the data from factor to numeric: 对于我的样本数据集,我使用以下代码将数据从系数转换为数值:

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

in order to then replace all NA values with 0s using this code: 然后使用此代码将所有NA值替换为0:

sample[is.na(sample)] = 0

however, when I convert from factor to numeric, the column names change and the rownames disappear. 然而,当我从要素转换为数值,列名发生变化, rownames消失。 why does this happen and how can I prevent it from happening when converting all columns to 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")

You can use data.frame instead of as.data.frame . 您可以使用data.frame而不是as.data.frame check.names=F tell the function to keep the column names. check.names=F告诉函数保留列名。 Use row.names to inherit the row names. 使用row.names继承行名称。

BTW, try not to use sample as a variable name in R as it is a reserved word of R. 顺便说一句,请不要在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

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

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