如何对数据框中的特定数据组执行mutate函数(ddply)?

时间:2015-12-10 20:36:25

标签: r plyr

我正在尝试使用ddply mutate函数将1添加到我的数据框的特定行。

具体问题
如果DurationtrackName,如何在experimenterTalk添加1(请参阅下面示例数据框中的第9行)?

以下是我的数据框的前几行。此数据框的名称为data_all

    Time Duration               trackName Comment
   (int)    (dbl)                  (fctr)  (fctr)
1  10173    0.500      playingCaterpillar  (null)
2  11092    0.399          playingChewToy  (null)
3  11946    0.413      playingSpinFanHand  (null)
4  12862    0.382           playingMirror  (null)
5  13651    0.413        playingButtonFan  (null)
6  14423    0.394 playingButtonFiberLight  (null)
7  15241    0.378  playingTwoButtonLights  (null)
8  16052    0.534           playingMagnet  (null)
9   8833    0.000        experimenterTalk  (null)
10  9295    0.585               totalPlay  (null)

以下是我的一次尝试:

    data_all_2 <- ddply(data_all, "trackName"=="experimenterTalk", mutate,
               Duration = Duration + 1
               )

但我收到此错误消息:

  Error in UseMethod("as.quoted") : 
  no applicable method for 'as.quoted' applied to an object of class "logical"

1 个答案:

答案 0 :(得分:1)

您尝试对数据进行子集化(过滤),而不需要包含分组变量。你实际上甚至不需要这里的分组变量。例如,在下面的代码而不是public class CollectionData { public static ObservableCollection<Client> GetData(Type type = null) { var clients = new ObservableCollection<Client>() { new Client() { Akronim = "Seifert", GidNumer = 4654 }, new Kontrahent() { Akronim = "Cenergo", GidNumer = 4656 } }; return clients; } } 中,您可以执行.(trackName)。但是,如果您这样做,.()将添加一个填充ddply的新.id列。

NA

data_all_2 = ddply(data_all, .(trackName) , mutate, Duration = ifelse(trackName=="experimenterTalk", Duration + 1, Duration)) 套餐速度更快,并且在很大程度上取代了dplyr

plyr

在基地R,您可以这样做:

library(dplyr)

data_all_2 = data_all %>% 
  mutate(Duration = ifelse(trackName=="experimenterTalk", Duration + 1, Duration)))