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:
sample[is.na(sample)] = 0
however, when I convert from factor to numeric, the column names change and the rownames
disappear. 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
. check.names=F
tell the function to keep the column names. Use row.names
to inherit the row names.
BTW, try not to use sample
as a variable name in R as it is a reserved word of 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.