我有這樣的數據幀,我想改變字符值NUM:R - 將chr值從多列轉換爲num?
> dput(Df)
structure(list(`@MeasurementDateGMT` = c("2016-09-01 00:00:00",
"2016-09-01 01:00:00", "2016-09-01 02:00:00", "2016-09-01 03:00:00",
"2016-09-01 04:00:00", "2016-09-01 05:00:00", "2016-09-01 06:00:00",
"2016-09-01 07:00:00", "2016-09-01 08:00:00", "2016-09-01 09:00:00",
"2016-09-01 10:00:00", "2016-09-01 11:00:00", "2016-09-01 12:00:00",
"2016-09-01 13:00:00", "2016-09-01 14:00:00", "2016-09-01 15:00:00",
"2016-09-01 16:00:00", "2016-09-01 17:00:00", "2016-09-01 18:00:00",
"2016-09-01 19:00:00", "2016-09-01 20:00:00", "2016-09-01 21:00:00",
"2016-09-01 22:00:00", "2016-09-01 23:00:00"), `@Value` = c("10.9",
"9.8", "9.9", "14.1", "13.6", "16.5", "15", "18.5", "18", "17",
"16.6", "12", "12.1", "18.1", "15.9", "15.9", "16.9", "21.6",
"23.5", "40.7", "16.6", "12.7", "12.4", "12.2")), .Names = c("@MeasurementDateGMT",
"@Value"), class = "data.frame", row.names = c(NA, 24L))
代碼轉換:
columns <- sapply(Df, is.factor)
Df[, columns] <- lapply(Df[, columns, drop = FALSE], function(x) as.numeric(as.character(x)))
結果:
> str(Df)
'data.frame': 24 obs. of 2 variables:
$ @MeasurementDateGMT: chr "2016-09-01 00:00:00" "2016-09-01 01:00:00" "2016-09-01 02:00:00" "2016-09-01 03:00:00" ...
$ @Value : chr "10.9" "9.8" "9.9" "14.1" ...
他們仍然chr
。我錯過了什麼?有任何想法嗎?
'columns'返回'c(FALSE,FALSE)'。你只是懶洋洋地將一種功能拋諸腦後。見'Df [,列]' – thelatemail
@ikop - 確切地說,OP的代碼工作正常。 as.numeric(as.character(...)實際上是轉換因子變量的好習慣,可惜在Df中沒有任何因素可以開始。: -/ – thelatemail
@thelatemail what結果應該'列'返回? – laukok