簡體   English   中英

在不影響行名/列名的情況下轉換所有列(將因子轉換為數字)

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

對於我的樣本數據集,我使用以下代碼將數據從系數轉換為數值:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM