R 如何通过唯一因子列获得平均值?
我有一个这样的数据框,有100多列:R 如何通过唯一因子列获得平均值?,r,R,我有一个这样的数据框,有100多列: ID regulation press treat 1001 test1 0.2 b 1001 test1 1 c 1002 test2 2 s 1002 test2 3 s 1004 test1 4 s 1004 test1 5 f 1005 test2 6 w 1006 test2 6 u 1006
ID regulation press treat
1001 test1 0.2 b
1001 test1 1 c
1002 test2 2 s
1002 test2 3 s
1004 test1 4 s
1004 test1 5 f
1005 test2 6 w
1006 test2 6 u
1006 test2 1 h
每个ID只有一个规则,数据库test1和test2中只有两个可能的规则
我基本上想求ID的所有唯一出现次数的总和
预期产量
test1: 2
test2: 3
也就是说,test1出现在2个唯一ID中,test2出现在3个唯一ID中。试试看
rowSums(table(unique(df[, c("regulation", "ID")])))
# test1 test2
# 2 3
或
或者使用dplyr
数据
除了阿克伦的回答,这是极好的;使用data.table方法可以很容易地做到这一点
library(data.table)
dt <- data.table(df)
rowSums(table(unique(dt[,ID, regulation])))
#test1 test2
#2 3
非常感谢。实际上,dataframe将有大量列,我只给出了我需要的两个列。如何使用行名称而不是2:1?@maximusyoda请在您的帖子中显示一个更新的示例,其中包含多个列和预期结果。这里2:1只是重新排列列。我又更新了两列。但基本上,dataframe有100个列。因此,我希望引用列本身的名称,而不是引用2:1。您是否也可以显示预期的输出。与调节栏相似吗?预期输出与之前相同。分析中不涉及新列。
library(dplyr)
count(unique(select(df, ID, regulation)), regulation)
#using the %>%, the above code would be
#df %>%
# select(ID, regulation)
# unique()
# count(regulation)
# regulation n
#1 test1 2
#2 test2 3
df <- structure(list(ID = c(1001L, 1001L, 1002L, 1002L, 1004L, 1004L,
1005L, 1006L, 1006L), regulation = c("test1", "test1", "test2",
"test2", "test1", "test1", "test2", "test2", "test2"), press = c(0.2,
1, 2, 3, 4, 5, 6, 6, 1), treat = c("b", "c", "s", "s", "s", "f",
"w", "u", "h")), .Names = c("ID", "regulation", "press", "treat"
), class = "data.frame", row.names = c(NA, -9L))
library(data.table)
dt <- data.table(df)
rowSums(table(unique(dt[,ID, regulation])))
#test1 test2
#2 3