I have a dataframe (mydf) that looks like this
I II
A 1.2 -2.1
B -2.3 4.2
C 3.8 -6.4
D 4.5 8.7
For some reason these values are not being considered numeric. So I tried using
mydm <- data.matrix(mydf)
to solve it. However, it returns
I II
A 2 1
B 3 2
C 8 4
D 5 7
data.matrix seems to have no other arguments related to this, so I feel pretty much stuck. Any workaround?
We can use
mydm[] <- (abs(mydm)* 10)%% 10
mydf[] <- lapply(mydf, as.numeric)
mydf <- data.matrix(mydf)
mydm <- structure(c(1.2, -2.3, 3.8, 4.5, -2.1, 4.2, -6.4, 8.7), .Dim = c(4L,
2L), .Dimnames = list(c("A", "B", "C", "D"), c("I", "II")))
Another base R option
mydm[] <- lapply(mydm, function(x) as.numeric(gsub("^.*\\.", "", x)))
Data
> dput(mydm)
structure(list(I = c(1.2, -2.3, 3.8, 4.5), II = c(-2.1, 4.2,
-6.4, 8.7)), class = "data.frame", row.names = c("A", "B", "C",
"D"))
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.