我想根据两列分割数据帧,但我希望输出是数据帧的二维矩阵,而不是数据帧的平面列表。我可以使用 by()
和 subset
实现我想要的目标,但有人告诉我(我认为是 Ripley)应该避免在中使用 subset
包开发。是否有一个优雅的替代方案(也许使用 split
)来保留暗名称?
# sample data
df <- data.frame(x=rnorm(20), y=rnorm(20), v1=rep(letters[1:5],each=4), v2=rep(LETTERS[6:9]))
# what I did previously
submat <- by(df, list(df$v1,df$v2), subset)
dim(submat) # 5 x 4
dimnames(submat) # "a" "b" "c" "d" "e" ; "F" "G" "H" "I"
最佳答案
要获得您所要求的数据帧矩阵,请使用 tapply
和一个返回特定数据帧子集但行名称与因子水平匹配的函数。
> dfmat <- with(df, tapply(1:NROW(df), list(v1,v2), function(idx) df[idx,] ) )
> dfmat[1,1] # items that are in a single dataframe accessed via matrix indexing
[[1]]
x y v1 v2
1 -0.5604756 -1.067824 a F
> dfmat
F G H I
a List,4 List,4 List,4 List,4
b List,4 List,4 List,4 List,4
c List,4 List,4 List,4 List,4
d List,4 List,4 List,4 List,4
e List,4 List,4 List,4 List,4
以列表作为条目的矩阵经过 print
编辑以仅显示对象类型和条目数(本例中为列)。请注意,每个条目都是一个包含一项的列表,因此保留了 dataframe 属性,但需要“向下钻取”才能获取宝藏:
编辑:添加 dfmat 的属性:
> attributes(dfmat)
$dim
[1] 5 4
$dimnames
$dimnames[[1]]
[1] "a" "b" "c" "d" "e"
$dimnames[[2]]
[1] "F" "G" "H" "I"
#------------
> attributes( dfmat[1,1])
NULL
#------------
> attributes( dfmat[1,1][[1]])
$names
[1] "x" "y" "v1" "v2"
$row.names
[1] 1
$class
[1] "data.frame"
关于r - 拆分 vs by + 子集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13632904/