【问题标题】:How can I sum rows that with non-numeric factor in R? [duplicate]如何对 R 中具有非数字因子的行求和? [复制]
【发布时间】:2016-02-10 03:27:41
【问题描述】:

我有这样的数据框:

   Port   Type
1  Port1   ssh
2  Port1   ftp
3  Port2  http
4  Port1  http
5  Port2   ssh
6  Port3   ssh
7  Port3 https
8  Port4  http
9  Port2   ftp
10 Port3   ssh
11 Port3   ftp
12 Port4   ssh

我想要这样的总和:

Port     ssh    ftp     http    https
Port1    1      1       1       0
Port2    1      1       1       0
Port3    2      1       0       1
Port4    1      0       0       1

我选择 R 是因为还有一些其他列有数值,我可以很方便地使用 R 来计算平均值/中位数/分位数。我搜索并找到了这个:Sum of rows based on column value,但是那里的代码似乎只适用于数字元素。

非常感谢您的回答。

【问题讨论】:

  • 第四行http应该是1,https应该是0

标签: r


【解决方案1】:

我们可以使用table

table(df1)
#          Type
#Port    ftp http https ssh
#  Port1   1    1     0   1
#  Port2   1    1     0   1
#  Port3   1    0     1   2
#  Port4   0    1     0   1

其他选项包括dcast

library(reshape2)
dcast(df1, Port~Type, value.var='Type', length)

【讨论】:

  • @LukeHuang 如果还有其他列,请将感兴趣的列子集并执行table。即table(df1[c('Type', 'Port')])
  • @LukeHuang 就像我之前在 cmets 中提到的那样,对感兴趣的列进行子集化。
  • 完美运行,谢谢@akrun。抱歉描述不好。
  • 嗨@akrun,如果所有端口中的https数量为0,即https根本不在数据框中,但我仍然想将其显示为全0,我该怎么办?谢谢。
  • @LukeHuang 一种选择是将“类型”列转换为factor 类并指定所有levels,然后执行table。即df1$Type <- factor(df1$Type, levels=c('ftp', 'http', 'https', 'ssh'));table(df1) 这将确保即使缺少一个级别,它也会显示所有 0'
猜你喜欢
  • 2021-09-27
  • 2018-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-21
  • 1970-01-01
相关资源
最近更新 更多