计算R中多个列的字符串出现次数

时间:2016-04-28 10:39:01

标签: r

我在R中有一个数据集,如下所示(仅显示相关列)。它有关于作物受访者想要了解更多信息的性别分类数据以及这种作物对他们的优先考虑。

sex     wantcropinfo1    priority1  wantcropinfo2     priority2 
m       wheat            high       eggplant          medium
m       rice             low        cabbage           high
m       rice             high
f       eggplant         medium
f       cotton           low
...    

我希望能够(a)计算所有wantcropinfoX列中每种作物的总出现次数; (b)获得相同的数量,但优先排序; (c)做同样的事情,但按性别分列。

(a)输出应如下所示:

 crop     count
 wheat    1
 eggplant 2
 rice     2
 ...

(b)输出应如下所示:

 crop     countm   countf
 wheat    1        0
 eggplant 1        1
 rice     2        0
 ...

(c)应如下所示:

 crop     high_m   med_m  low_m  high_f   med_f   low_f
 wheat    1        0      0      0        0       0
 eggplant 0        1      0      0        1       0
 rice     1        0      1      0        0       0
 ...

我有点像R新手,手册略显扑朔迷离。我已经搜索了很多东西但是找不到任何类似的东西,即使它似乎是一个人们可能想要做的相当普遍的事情。 stackoverflow上的类似问题似乎在问一些不同的东西。

2 个答案:

答案 0 :(得分:2)

我们可以使用melt中的data.table来转换广泛的'长期'格式。它可能需要多个measure列。

library(data.table)
dM <- melt(setDT(df1), measure = patterns("^want", "priority"),
       value.name = c("crop", "priority"))[crop!='']

在&#39;长期&#39;格式,我们通过&#39; crop&#39;分组获得3个预期结果。获取行数或转换为&#39; wide&#39; dcast将fun.aggregate指定为length

dM[,.(count= .N) , crop]
#       crop count
#1:    wheat     1
#2:     rice     2
#3: eggplant     2
#4:   cotton     1
#5:  cabbage     1

dcast(dM, crop~sex, value.var='sex', length)
#       crop f m
#1:  cabbage 0 1
#2:   cotton 1 0
#3: eggplant 1 1
#4:     rice 0 2
#5:    wheat 0 1

dcast(dM, crop~priority+sex, value.var='priority', length)
#       crop high_m low_f low_m medium_f medium_m
#1:  cabbage      1     0     0        0        0
#2:   cotton      0     1     0        0        0
#3: eggplant      0     0     0        1        1
#4:     rice      1     0     1        0        0
#5:    wheat      1     0     0        0        0

答案 1 :(得分:1)

ddply包中使用plyr功能。

您使用此功能的方式如下:

ddply(dataframe,.(var1,var2,...), summarize, function)

在这种情况下,您可能需要执行以下操作:

  1. a)ddply(df,.(wantcropinfo1),summarize,count=length(wantcropinfo1))
  2. B)ddply(df,.(wantcropinfo1,priority),summarize,count=length(wantcropinfo1))
  3. c)ddply(df,.(wantcropinfo1,priority,sex),summarize,count=length(wantcropinfo1))
  4. 请注意,输出与您在问题中提到的结构不同,但信息将相同。对于上述结构,请使用table函数

相关问题