R中的计数函数
Counting function in R
我有这样的数据集
id <- 1:12
b <- c(0,0,1,2,0,1,1,2,2,0,2,2)
c <- rep(NA,3)
d <- rep(NA,3)
df <-data.frame(id,b)
newdf <- data.frame(c,d)
我想做简单的数学运算。如果 x==1 或 x==2 计算它们并写出此数据集中有多少个 1 和 2。但我不想计算整个数据集,我希望我的函数四乘四地计算它们。
我想要这样的结果:
> newdf
one two
1 1 1
2 2 1
3 0 3
我尝试了很多变体,但没有成功。
afonk <- function(x) {
ifelse(x==1 | x==2, x, newdf <- (x[1]+x[2]))
}
afonk(newdf$one)
lapply(newdf, afonk)
提前致谢!
伊斯梅尔
我们可以使用 data.table
中的 dcast
。使用 %/%
然后 dcast
从 'long' 到 'wide' 格式创建分组变量。
library(data.table)
dcast(setDT(df)[,.N ,.(grp=(id-1)%/%4+1L, b)],
grp~b, value.var='N', fill =0)[,c(2,4), with=FALSE]
或者更紧凑的版本将使用 fun.aggregate
作为 length
。
res <- dcast(setDT(df)[,list((id-1)%/%4+1L, b)][b!=0],
V1~b, length)[,V1:=NULL][]
res
# 1 2
#1: 1 1
#2: 2 1
#3: 0 3
如果我们需要列名是'one','two'
library(english)
names(res) <- as.character(english(as.numeric(names(res))))
基础 R 的乐趣:
# counting function
countnum <- function(x,num){
sum(x == num)
}
# make list of groups of 4
df$group <- rep(1:ceiling(nrow(df)/4),each = 4)[1:nrow(df)]
dfl <- split(df$b,f = df$group)
# make data frame of counts
newdf <- data.frame(one = sapply(dfl,countnum,1),
two = sapply(dfl,countnum,2))
根据评论编辑:
# make list of groups of 4
df$group <- rep(1:ceiling(nrow(df)/4),each = 4)[1:nrow(df)]
table(subset(df, b != 0L)[c("group", "b")])
您喜欢哪种取决于您需要哪种类型的结果。 table 适用于较小的视觉计数,您可能可以从 table 中提取数据,但如果它像您的示例一样简单,您可能会选择 data.frame .
我有这样的数据集
id <- 1:12
b <- c(0,0,1,2,0,1,1,2,2,0,2,2)
c <- rep(NA,3)
d <- rep(NA,3)
df <-data.frame(id,b)
newdf <- data.frame(c,d)
我想做简单的数学运算。如果 x==1 或 x==2 计算它们并写出此数据集中有多少个 1 和 2。但我不想计算整个数据集,我希望我的函数四乘四地计算它们。
我想要这样的结果:
> newdf
one two
1 1 1
2 2 1
3 0 3
我尝试了很多变体,但没有成功。
afonk <- function(x) {
ifelse(x==1 | x==2, x, newdf <- (x[1]+x[2]))
}
afonk(newdf$one)
lapply(newdf, afonk)
提前致谢!
伊斯梅尔
我们可以使用 data.table
中的 dcast
。使用 %/%
然后 dcast
从 'long' 到 'wide' 格式创建分组变量。
library(data.table)
dcast(setDT(df)[,.N ,.(grp=(id-1)%/%4+1L, b)],
grp~b, value.var='N', fill =0)[,c(2,4), with=FALSE]
或者更紧凑的版本将使用 fun.aggregate
作为 length
。
res <- dcast(setDT(df)[,list((id-1)%/%4+1L, b)][b!=0],
V1~b, length)[,V1:=NULL][]
res
# 1 2
#1: 1 1
#2: 2 1
#3: 0 3
如果我们需要列名是'one','two'
library(english)
names(res) <- as.character(english(as.numeric(names(res))))
基础 R 的乐趣:
# counting function
countnum <- function(x,num){
sum(x == num)
}
# make list of groups of 4
df$group <- rep(1:ceiling(nrow(df)/4),each = 4)[1:nrow(df)]
dfl <- split(df$b,f = df$group)
# make data frame of counts
newdf <- data.frame(one = sapply(dfl,countnum,1),
two = sapply(dfl,countnum,2))
根据评论编辑:
# make list of groups of 4
df$group <- rep(1:ceiling(nrow(df)/4),each = 4)[1:nrow(df)]
table(subset(df, b != 0L)[c("group", "b")])
您喜欢哪种取决于您需要哪种类型的结果。 table 适用于较小的视觉计数,您可能可以从 table 中提取数据,但如果它像您的示例一样简单,您可能会选择 data.frame .