在R中创建透视表
我知道这已经被问了很多次了,但我在过去的两天里浏览了互联网,找不到创建数据透视表或汇总表所需的帮助,就像使用excel一样。我是一个完全不懂R的新手,所以我发现R包帮助文件中的大多数示例都太复杂了 我有一个数据列表(“集合”),如下所示在R中创建透视表,r,pivot-table,percentage,R,Pivot Table,Percentage,我知道这已经被问了很多次了,但我在过去的两天里浏览了互联网,找不到创建数据透视表或汇总表所需的帮助,就像使用excel一样。我是一个完全不懂R的新手,所以我发现R包帮助文件中的大多数示例都太复杂了 我有一个数据列表(“集合”),如下所示 Phase class NISP <chr> <chr> <int> 1 L Aves 11 2 L Fish 128 3 L Mammals 14 4
Phase class NISP
<chr> <chr> <int>
1 L Aves 11
2 L Fish 128
3 L Mammals 14
4 K Aves 63
5 K Fish 30
6 K Mammals 311
7 J Aves 170
8 J Fish 327
9 J Mammals 740
10 I Aves 45
# ... with 18 more rows
但我现在不明白我需要的是:
- 将(全部)替换为“总计”
- 按以下顺序排列列(“阶段”、“哺乳动物”、“鱼类”、“鸟类”、“不确定”、“总计”)
- 添加新列,其中包含每个阶段每个动物类别的百分比(占行总数的百分比)
- 下面的代码应该一步一步地完成所有工作。如果有什么不清楚的地方,请告诉我
# make some data
df = data.frame(Phase = c(1, 1, 2, 2, 3),
Fish = floor(rnorm(5, 150)),
Mammal = floor(rnorm(5, 50)))
df$all = rowSums(df[, 2:3])
# 1 change name
names(df)[which(names(df) == 'all')] = 'Total'
# 2 - reverse Fish and Mammal
idx1 = 2:3 # columns to change
idx2 = 3:2 # new order of columns
df[, idx1] = df[, idx2]
names(df)[idx1] = names(df)[idx2]
# 3 - calculate percentages
idxT = 2:3 # column indices of interest
newColNames = paste('%', names(df)[idxT])
tmp = df[, idxT, drop = FALSE] / matrix(df["Total"], ncol = length(idxT))
colnames(tmp) = newColNames
df = cbind(df, tmp)
那太好了,谢谢,这几乎可以解决所有问题。进口乳胶会有一些整理工作要做,但目前还可以。很高兴听到这个消息。如果您想在APA指南中使用Latex,我建议您看看R包
xtable
。它有一个函数xtable
,该函数将矩阵或数据帧作为参数,并返回一个APA格式的latex表。
Phase Aves Fish Indeterminate Mammals (all)
1 A 1 0 0 6 7
2 B 2 0 0 3 5
3 C 58 20 0 255 333
4 E 5 2 0 5 12
5 F 14 0 0 17 31
6 H 121 154 1 784 1060
7 I 45 110 0 149 304
8 J 170 327 0 740 1237
9 K 63 30 0 311 404
10 L 11 128 0 14 153
11 (all) 490 771 1 2284 3546
# make some data
df = data.frame(Phase = c(1, 1, 2, 2, 3),
Fish = floor(rnorm(5, 150)),
Mammal = floor(rnorm(5, 50)))
df$all = rowSums(df[, 2:3])
# 1 change name
names(df)[which(names(df) == 'all')] = 'Total'
# 2 - reverse Fish and Mammal
idx1 = 2:3 # columns to change
idx2 = 3:2 # new order of columns
df[, idx1] = df[, idx2]
names(df)[idx1] = names(df)[idx2]
# 3 - calculate percentages
idxT = 2:3 # column indices of interest
newColNames = paste('%', names(df)[idxT])
tmp = df[, idxT, drop = FALSE] / matrix(df["Total"], ncol = length(idxT))
colnames(tmp) = newColNames
df = cbind(df, tmp)