我有如下創建的資料框串列:
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
輸出如下:
[[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
我希望將資料框中的變數名稱自動分配給 l3 串列元素。例如:串列 1 中的 Var1 變為 x。串列 2 中的 Var1 變為 y。串列 3 中的 Var1 變為 m。謝謝
uj5u.com熱心網友回復:
使用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
資料:
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")
uj5u.com熱心網友回復:
一種可能的解決方案:
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/528648.html
標籤:r列表数据框多列改名
