Insert rownames/ values as a new variable in a list dataframes

Asked

Viewed 248 times

1

Suppose n dataframes within a list. Each of these dataframes has different lines. For example, in a dataframe, rownames are characters (make of cars) and in other, rownames These are hospital registration numbers. My goal is to transfer each of these rownames into their respective dataframe, as a variable, and into the list. This is:

dados$newvariable<-rownames(dados)

not interesting, because I have to type this for each dataframe.

dput to assist resolution:

list(structure(list(modelo = structure(1:5, .Label = c("a", "b", 
"c", "d", "e"), class = "factor"), valor = c(5000, 10000, 15000, 
20000, 25000)), .Names = c("modelo", "valor"), row.names = c("Fiat", 
"Chevrolet", "Volkswagen", "Renault", "Ford"), class = "data.frame"), 
structure(list(convenio = structure(1:6, .Label = c("a", 
"b", "c", "d", "e", "f"), class = "factor"), valor = c(150, 
300, 450, 600, 750, 900)), .Names = c("convenio", "valor"
), row.names = c("17242", "60003", "50215", "54345", "11246", 
"45432"), class = "data.frame"))

1 answer

2


You can fix that with a loop.

dados =  list(structure(list(modelo = structure(1:5, .Label = c("a", "b", 
    "c", "d", "e"), class = "factor"), valor = c(5000, 10000, 15000, 
    20000, 25000)), .Names = c("modelo", "valor"), row.names = c("Fiat", 
    "Chevrolet", "Volkswagen", "Renault", "Ford"), class = "data.frame"), 
    structure(list(convenio = structure(1:6, .Label = c("a", 
    "b", "c", "d", "e", "f"), class = "factor"), valor = c(150, 
    300, 450, 600, 750, 900)), .Names = c("convenio", "valor"
    ), row.names = c("17242", "60003", "50215", "54345", "11246", 
    "45432"), class = "data.frame"))

dados
#[[1]]
#           modelo valor
#Fiat            a  5000
#Chevrolet       b 10000
#Volkswagen      c 15000
#Renault         d 20000
#Ford            e 25000

#[[2]]
#      convenio valor
#17242        a   150
#60003        b   300
#50215        c   450
#54345        d   600
#11246        e   750
#45432        f   900

for (i in 1:length(dados)) {
  x = rownames(as.data.frame(dados[i]))
  n = ncol(as.data.frame(dados[i])) + 1
  dados[[i]][n] = x
}

dados

#[[1]]
#           modelo valor         V3
#Fiat            a  5000       Fiat
#Chevrolet       b 10000  Chevrolet
#Volkswagen      c 15000 Volkswagen
#Renault         d 20000    Renault
#Ford            e 25000       Ford

#[[2]]
#      convenio valor    V3
#17242        a   150 17242
#60003        b   300 60003
#50215        c   450 50215
#54345        d   600 54345
#11246        e   750 11246
#45432        f   900 45432

Browser other questions tagged

You are not signed in. Login or sign up in order to post.