对于另一行的每个值,不计算某列的值的NA [英] Counting not NA's for values of some column for each value of another row

查看:54
本文介绍了对于另一行的每个值,不计算某列的值的NA的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在R语言中-我可以说我有一个DF,其中有两列 Fam Prop 都是分类的,现在 Fam 具有重复的名称例如Algea,Fungi等,"Prop"列具有分类编号和NA.我如何获得一个表/输出,对于每个A值,它告诉我没有多少个值. 不适用的示例:

In R language - I have lets say I have a DF with two columns Fam and Prop both categorical, now Fam has repeated names like Algea, Fungi, etc and column Prop has categorical numbers and NA's. How can I get a table/output that for each value of A it tells me how many values are not. NA example:

    Fam     Prop
    -------------
    Algea   one
    Fungi   two
    Algea   NA
    Algea   three
    Fungi   one
    Fungi   NA

输出:

Algea 2
Fungi 2

我知道使用count函数应该是解决方案的指导,但似乎无法解决,因为Fam列具有重复值.

I know using the count function should be a direction for the solution but can't seem to solve it, because the Fam column has repeating values.

推荐答案

四种解决方案:

基本R帧:

aggregate(DF$Prop, by=list(Fam=DF$Fam), FUN=function(a) sum(!is.na(a)))
#   Fam x
# 1   A 5
# 2   B 6
# 3   C 4

基本R,表格"(不是框架,请参见as.data.frame(xtabs(...))以查看框架变体……有点不同):

Base R, "table" (which is not a frame, see as.data.frame(xtabs(...)) to see the frame variant ... a little different):

xtabs(~ Fam + is.na(Prop), data=DF)
#    is.na(Prop)
# Fam FALSE TRUE
#   A     5    1
#   B     6    1
#   C     4    3

dplyr:

library(dplyr)
DF %>%
  group_by(Fam) %>%
  summarize(n = sum(!is.na(Prop)))
# # A tibble: 3 x 2
#   Fam       n
#   <fct> <int>
# 1 A         5
# 2 B         6
# 3 C         4

data.table

library(data.table)
# data.table 1.11.4  Latest news: http://r-datatable.com
# Attaching package: 'data.table'
# The following objects are masked from 'package:dplyr':
#     between, first, last
DT <- as.data.table(DF)
DT[,sum(!is.na(Prop)),keyby=.(Fam)]
#    Fam V1
# 1:   A  5
# 2:   B  6
# 3:   C  4


数据:


Data:

DF <- data.frame(Fam=sample(c('A','B','C'), size=20, replace=TRUE), Prop=sample(c('one','two','three'), size=20, replace=TRUE))
DF$Prop[sample(20,size=5)] <- NA
DF
#    Fam  Prop
# 1    B   one
# 2    B three
# 3    C  <NA>
# 4    A  <NA>
# 5    C   one
# 6    A   two
# 7    B   one
# 8    A three
# 9    B   two
# 10   C   one
# 11   C   two
# 12   B three
# 13   C  <NA>
# 14   C  <NA>
# 15   A   one
# 16   A   one
# 17   B three
# 18   A   two
# 19   C   two
# 20   B  <NA>

这篇关于对于另一行的每个值,不计算某列的值的NA的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆