Home > Blockchain >  How to change the names of columns of a list of dataframes?
How to change the names of columns of a list of dataframes?

Time:11-07

I have this list of dataframes created as follows :

df = data.frame(x = c(1,0,0,0,1,1,1,NA), y = c(2,2,2,2,3,3,2,NA),
                z = c(1:7,NA), m = c(1,2,3,1,2,3,1,NA) )

df$x = factor(df$x)
df$y = factor(df$y)
df$m = factor(df$m)

l1 = list(df$x,df$y,df$m)
l2 = lapply(l1,table)
l3 = lapply(l2,as.data.frame)
l3

The output is as follows :

[[1]]
  Var1 Freq
1    0    3
2    1    4

[[2]]
  Var1 Freq
1    2    5
2    3    2

[[3]]
  Var1 Freq
1    1    3
2    2    2
3    3    2


I wish that the names of the variables from the dataframe are assigned autmatically to the l3 list elements. For example : Var1 from list 1 becomes x. Var1 from list 2 becomes y. Var1 from list 3 becomes m. Thanks

CodePudding user response:

Using Map.

l3 <- lapply(df, table) |> lapply(as.data.frame)
(l3 <- Map(\(x, y) {names(x)[1] <- y; x}, l3, names(l3)))
# $x
#   x Freq
# 1 0    3
# 2 1    4
# 
# $y
#   y Freq
# 1 2    5
# 2 3    2
# 
# $z
#   z Freq
# 1 1    1
# 2 2    1
# 3 3    1
# 4 4    1
# 5 5    1
# 6 6    1
# 7 7    1
# 
# $m
#   m Freq
# 1 1    3
# 2 2    2
# 3 3    2

Data:

df <- structure(list(x = structure(c(2L, 1L, 1L, 1L, 2L, 2L, 2L, NA
), levels = c("0", "1"), class = "factor"), y = structure(c(1L, 
1L, 1L, 1L, 2L, 2L, 1L, NA), levels = c("2", "3"), class = "factor"), 
    z = c(1L, 2L, 3L, 4L, 5L, 6L, 7L, NA), m = structure(c(1L, 
    2L, 3L, 1L, 2L, 3L, 1L, NA), levels = c("1", "2", "3"), class = "factor")), row.names = c(NA, 
-8L), class = "data.frame")

CodePudding user response:

One possible solution:

Map(\(x,y) setNames(x, c(y,"Freq")), l3, c("x", "y", "z"))


[[1]]
  x Freq
1 0 3
2 1 4

[[2]]
  y Freq
1 2 5
2 3 2

[[3]]
  z Freq
1 1 3
2 2 2
3 3 2
  • Related