Insert the names / values of 'rownames' as a new variable in dataframes of a list

1

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

dados$newvariable<-rownames(dados)

It's not interesting, as I have to type this for each dataframe.

dput to aid 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"))
    
asked by anonymous 11.09.2018 / 03:24

1 answer

2

This can be solved 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
    
11.09.2018 / 04:21