r语言 - 根据变量名将不相等列表组合成data.frame对象



很琐碎的任务,但找不到答案,并努力找到合适的解决方案。

我想将许多不同的变量(列表)包含不等数量的字符串数据合并到单个data.frame对象中,其中第一列获得变量名,第二列获得分配值。


Variable_1
name
1    actor_id
2  first_name
3   last_name
4 last_update

Variable_2

name
1  address_id
2     address
3    address2
4    district
5     city_id
6 postal_code
7       phone
8 last_update

Expectd输出:

1 Variable_1 actor_id
2 Variable_1 first_name
3 Variable_1 last_name
4 Variable_1 last_update
5 Variable_2 address_id
6 Variable_2 address
7 Variable_2 address2
8 Variable_2 district
9 Variable_2 city_id
10 Variable_2 postal_code
11 Variable_2 phone
12 Variable_2 last_update

我打赌一定有多种方法。谢谢你的提示!

假设命名了list对象,用do.callnamesrbind(list)元素创建一个新列

out <- do.call(rbind, Map(cbind, varname = names(lst1), lst1))
row.names(out) <- NULL

或者我们可以使用bind_rows

library(purrr)
library(dplyr)
bind_rows(lst1, .id = 'varname') %>%
as_tibble

数据
lst1 <- list(Variable_1 = structure(list(name = c("actor_id", "first_name", 
"last_name", "last_update")), class = "data.frame", row.names = c("1", 
"2", "3", "4")), Variable_2 = structure(list(name = c("address_id", 
"address", "address2", "district", "city_id", "postal_code", 
"phone", "last_update")), class = "data.frame", row.names = c("1", 
"2", "3", "4", "5", "6", "7", "8")))

示例数据

variable1 <- paste0("variable1_",1:2)
variable2 <- paste0("variable2_",1:3)

如何

expand.grid(variable1,variable2)
结果

Var1        Var2
1 variable1_1 variable2_1
2 variable1_2 variable2_1
3 variable1_1 variable2_2
4 variable1_2 variable2_2
5 variable1_1 variable2_3
6 variable1_2 variable2_3

相关内容

  • 没有找到相关文章

最新更新