我有一个使用代码从列表“ y”创建的data.frame
map_dfr(y, ~as.data.frame(t(.x)))
该格式对我有用,但是数据帧的每一列本身都是一个列表,而不是我希望的矢量。我该怎么做才能弄平每个列表,以便保留数据框的结构,但更改每个列的格式?
编辑:这是其当前格式的一小部分数据。我想要做的是将每个变量都取消列出到向量中,以便采用正常的data.frame格式。
structure(list(member_id = list("A000055", "A000361", "A000367",
"A000369", "A000210", "B001256", "B000013", "B001279", "B001269",
"B001282"), name = list("Robert B. Aderholt", "Rodney Alexander",
"Justin Amash", "Mark Amodei", "Robert E. Andrews", "Michele Bachmann",
"Spencer Bachus", "Ron Barber", "Lou Barletta", "Andy Barr"),
party = list("R", "R", "R", "R", "D", "R", "R", "D", "R",
"R"), state = list("AL", "LA", "MI", "NV", "NJ", "MN",
"AL", "AZ", "PA", "KY"), district = list("4", "5", "3",
"2", "1", "6", "6", "2", "11", "6"), cook_pvi = list(
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL), vote_position = list("No", "Yes", "No", "Yes",
"Yes", "No", "Yes", "Yes", "Yes", "Yes"), dw_nominate = list(
0.361, 0.331, 0.649, 0.376, -0.297, 0.584, 0.387, -0.123,
0.277, 0.485), bill_num = c("S47", "S47", "S47", "S47",
"S47", "S47", "S47", "S47", "S47", "S47"), bill_title = c("Violence Against Women Reauthorization Act of 2013",
"Violence Against Women Reauthorization Act of 2013", "Violence Against Women Reauthorization Act of 2013",
"Violence Against Women Reauthorization Act of 2013", "Violence Against Women Reauthorization Act of 2013",
"Violence Against Women Reauthorization Act of 2013", "Violence Against Women Reauthorization Act of 2013",
"Violence Against Women Reauthorization Act of 2013", "Violence Against Women Reauthorization Act of 2013",
"Violence Against Women Reauthorization Act of 2013")), row.names = c(NA, 10L), class = "data.frame")
可能这就是您想要的:
y[] <- lapply(y, unlist)
这会将数据转换为普通的data.frame格式。
str(y)
#'data.frame': 10 obs. of 9 variables:
# $ member_id : chr "A000055" "A000361" "A000367" "A000369" ...
# $ name : chr "Robert B. Aderholt" "Rodney Alexander" "Justin Amash" "Mark Amodei" ...
# $ party : chr "R" "R" "R" "R" ...
# $ state : chr "AL" "LA" "MI" "NV" ...
# $ district : chr "4" "5" "3" "2" ...
# $ vote_position: chr "No" "Yes" "No" "Yes" ...
# $ dw_nominate : num 0.361 0.331 0.649 0.376 -0.297 0.584 0.387 -0.123 0.277 0.485
#$ bill_num : chr "S47" "S47" "S47" "S47" ...
# $ bill_title : chr "Violence Against Women Reauthorization Act of 2013" "Violence Against Women Reauthorization Act of 2013" "Violence Against Women Reauthorization Act of 2013" "Violence Against Women Reauthorization Act of 2013" ...
如果我们有多个长度的列表,我们可以使用unnest
并传递一定范围的列。
library(tidyr)
library(dplyr)
z <- y %>%
unnest(cols = member_id:district) %>%
type.convert(as.is = TRUE) %>%
arrange(desc(district))
我们可以使用arrange(district)
升序对它们进行排序。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句