R How to count occurrences of values across multiple columns of a data frame and save the columnwise counts from a particular value as a new row?

China☆狼群 提交于 2019-12-06 10:59:53

you can apply a function to all the column of you data.frame. Suppose you want to count the number of 'A' in each column of the data.frame d

#a sample data.frame
    L3 <- LETTERS[1:3]
     (d <- data.frame(cbind(x = 1, y = 1:10), fac = sample(L3, 10, replace = TRUE)))



# the function you are looking for
    apply(X=d,2,FUN=function(x) length(which(x=='A')))

Very similar to @Jilber. Assumes your data is in a data frame df.

lst      <- colnames(df[,-(1:2)])
count.na <- sapply(lst,FUN=function(x,df){sum(is.na(df[,x]))},df)
count.00 <- sapply(lst,FUN=function(x,df){sum(df[,x]==0,na.rm=T)},df)
count.05 <- sapply(lst,FUN=function(x,df){sum(df[,x]==0.5,na.rm=T)},df)
count.10 <- sapply(lst,FUN=function(x,df){sum(df[,x]==1.0,na.rm=T)},df)

df <- rbind(df, 
            c(NA,NA,count.na), 
            c(NA,NA,count.00), 
            c(NA,NA,count.05), 
            c(NA,NA,count.10))

You would probably want to replace the NA's in the last rbind(...) statement with something that identifies what you are counting.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!