1

定义:

> 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

我想从每个数据框中的 b 列中删除 M 字符。

在一个简单的框架中:

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

但是在嵌套中,如何进行?这是一个抱歉的尝试:

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

3 回答 3

2

你可以用lapply(和一些强制)来做到这一点:

stripM <- function(x){
x$b <- substr(as.character(x$b),1,nchar(as.character(x$b))-1)
x
}
lapply(dats,FUN=stripM)

如果您需要该变量作为一个因子,您可以在其中包含一行stripMconverts is back to a factor,例如x$b <- as.factor(x$b).

于 2011-06-19T00:23:06.770 回答
2

尝试使用gsub而不是substr- 像这样的东西:

lapply(<data.frame or list>, function(x) as.numeric(gsub("M$", "", x)))

当然,你需要弄清楚你将如何递归到列表元素等,但我想你明白了......

于 2011-06-19T01:15:54.507 回答
0

好的,这是另一种可能性,不简洁,但可以理解:

for(i in seq(along=dats)) {
    c <- as.character(dats[[i]][["b"]])
    c <- substr(c, 1, nchar(c)-1)
    dats[[i]][["b"]] <- c
    dats
}
dats

我不得不说,我发现整体[[[引用非常神秘。

> str(dats[[i]][["b"]])
 chr [1:3] "325.049072" "325.049072" "325.049072"
> str(dats[[i]]["b"])
'data.frame':   3 obs. of  1 variable:
 $ b: chr  "325.049072" "325.049072" "325.049072"

我通过反复试验进行。任何指向一个好的解释的指针?

于 2011-06-19T00:32:16.430 回答