如何对R中具有非数字因子的行求和?
我有这样的数据框:如何对R中具有非数字因子的行求和?,r,R,我有这样的数据框: 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
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
我想要一个这样的总数:
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非常方便地计算平均值/中值/分位数。我搜索并找到了:,但是那里的代码似乎只对数字元素起作用
非常感谢您的回答。我们可以使用
表格
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)
我们可以只使用
表格
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)
在第四行中,
http
应为1,而https
应为0。在第四行中,http
应为1,而https
应为00@LukeHuang如果还有其他列,则将感兴趣的列子集,然后执行表
。i、 e.table(df1[c('Type','Port'))
@LukeHuang只需对我前面在评论中提到的感兴趣的列进行子集设置。非常有效,谢谢@akrun。抱歉,描述不正确。您好@akrun,如果所有端口中的https数量都是0,则表示https根本不在数据帧中,但我仍然希望将其显示为所有0,我可以做什么?谢谢。@LukeHuang一个选项是将“Type”列转换为指定了所有级别的factor
类,然后执行表
。i、 e.df1$Type@LukeHuang如果还有其他列,将感兴趣的列子集并执行表
。i、 e.table(df1[c('Type','Port'))
@LukeHuang只需对我前面在评论中提到的感兴趣的列进行子集设置。非常有效,谢谢@akrun。抱歉,描述不正确。您好@akrun,如果所有端口中的https数量都是0,则表示https根本不在数据帧中,但我仍然希望将其显示为所有0,我可以做什么?谢谢。@LukeHuang一个选项是将“Type”列转换为指定了所有级别的factor
类,然后执行表
。i、 e.df1$类型