Question

Define:

> dats <- list( df1 = data.frame(a=sample(1:3), b = as.factor(rep("325.049072M",3))),
+       df2 = data.frame(a=sample(1:3), b = as.factor(rep("325.049072M",3))))
> dats
$df1
  a           b
1 3 325.049072M
2 2 325.049072M
3 1 325.049072M

$df2
  a           b
1 2 325.049072M
2 1 325.049072M
3 3 325.049072M

I want to remove the M character from column b in each data frame.

In a simple framework:

> t<-c("325.049072M","325.049072M")
> t
[1] "325.049072M" "325.049072M"
> t <- substr(t, 1, nchar(t)-1)
> t
[1] "325.049072" "325.049072"

But in a nested one, how to proceed? Here is one sorry attempt:

> dats <- list( df1 = data.frame(a=sample(1:3), b = as.factor(rep("325.049072M",3))),
+       df2 = data.frame(a=sample(1:3), b = as.factor(rep("325.049072M",3))))
> dats
$df1
  a           b
1 3 325.049072M
2 1 325.049072M
3 2 325.049072M

$df2
  a           b
1 2 325.049072M
2 3 325.049072M
3 1 325.049072M

> for(i in seq(along=dats)) {
+   dats[[i]]["b"] <- 
+           substr(dats[[i]]["b"], 1, nchar(dats[[i]]["b"])-1)
+ }
> dats
$df1
  a         b
1 3 c(1, 1, 1
2 1 c(1, 1, 1
3 2 c(1, 1, 1

$df2
  a         b
1 2 c(1, 1, 1
2 3 c(1, 1, 1
3 1 c(1, 1, 1

No correct solution

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top