r - 拆分 vs by + 子集

标签 r split names

我想根据两列分割数据帧,但我希望输出是数据帧的二维矩阵,而不是数据帧的平面列表。我可以使用 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/

相关文章:

r - 使用 ggplot 在多个 geom_point 组周围绘制轮廓

java - 打印分割字符串

javascript - 将路径字符串从 unc 转换为 uri,在 Google Apps 脚本中用反斜杠替换斜杠

arrays - R 中的 3 维数组名称

javascript - 在另一个 json 对象(不是数组)中获取 json 对象

r - 在 lattice xyplot 中绘制每组面板数据的第一个点

r - 窗口变化的移动平均线

r - 合并两个数据框,同时保持原始行顺序

r - 尝试从 R 中的基因序列返回指定数量的字符

maven : deploy artifact file name