Modifica delle voci delle celle in una variabile in un frame di dati all'interno di un elenco di frame di dati

StackOverflow https://stackoverflow.com/questions/6399689

Domanda

Definire:

> 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

Voglio rimuovere il carattere M dalla colonna B in ciascun frame di dati.

In un framework semplice:

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

Ma in un nidificato, come procedere? Ecco un tentativo scusa:

> 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

Nessuna soluzione corretta

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top