我的数据在R
中具有以下形式data<-list(list(Name= "Value1",corresponding_set=c(1,2,3)), list(Name="AnotherKey",corresponding_set=c(4,5,3,4)))
我想要获得的是格式数据框
1 2 3 4 5
Key 1 1 1 0 0
AnotherKey 0 0 1 2 1
我尝试了以下内容:
myfunc<-function(x){
currValue<-x$corresponding_Set
for(i in 1:5){
print(c(i,sum(currValue==i))
}
}
sapply(data,myfunc)
上面的代码确实打印了我需要的值,但格式如下
1 1
2 1
3 1
4 0
5 1
1 0
2 0
3 0
4 2
5 1
我的问题是
任何帮助表示赞赏!
答案 0 :(得分:2)
您可以将嵌套的lists
转换为data.frames
,将它们绑定在一起然后调用table
来获得您要查找的结果。
data <- list(list(Name = "Value1",
corresponding_set = c(1, 2, 3)),
list(Name = "AnotherKey",
corresponding_set = c(4, 5, 3, 4)))
# Convert each list element to a data.frame
dfs <- lapply(data, as.data.frame)
dfs
# [[1]]
# Name corresponding_set
# 1 Value1 1
# 2 Value1 2
# 3 Value1 3
#
# [[2]]
# Name corresponding_set
# 1 AnotherKey 4
# 2 AnotherKey 5
# 3 AnotherKey 3
# 4 AnotherKey 4
# bind the two data.frames together
df <- do.call(rbind, dfs)
df
# Name corresponding_set
# 1 Value1 1
# 2 Value1 2
# 3 Value1 3
# 4 AnotherKey 4
# 5 AnotherKey 5
# 6 AnotherKey 3
# 7 AnotherKey 4
# build a table
table(df)
# corresponding_set
# Name 1 2 3 4 5
# AnotherKey 0 0 1 2 1
# Value1 1 1 1 0 0