0

背景:我有一个数据框,其中一列具有重复值。我试图通过挑选具有重复列值的所有行来拆分此数据框,处理它们,然后吐出一个包含所有已处理行的新数据框。

我很惊讶以下代码中出了什么问题:

    dataSet <- structure(list(DAY = structure(1:10, .Label = c("Tuesday", 
    "Tuesday", "Tuesday", "Tuesday", "Tuesday", 
    "Tuesday", "Tuesday", "Tuesday", "Tuesday", 
    "Tuesday", "Tuesday", "Tuesday", "Tuesday", 
    "Tuesday", "Tuesday", "Tuesday", "Tuesday", 
    "Tuesday", "Tuesday", "Tuesday", "Tuesday", 
    "Tuesday", "Tuesday", "Tuesday"), class = "factor"), 
        variable = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
        1L), .Label = c("act1", "act2", "act3", "act4", 
        "act5", "act12", "act19", "act116", "act22", 
        "act6", "act13", "act111", "act117", "act23", 
        "act7", "act14", "act112", "act118", "act24", 
        "act8", "act15", "act113", "act119", "act25", 
        "act9", "act16", "act114", "act20", "act26", 
        "act10", "act17", "act115", "act21", "act27", 
        "act11", "act18"), class = "factor"), value = c(67, 
        65, 40, 79, 106, 90, 57, 59, 2, 12)), .Names = c("DAY", 
    "variable", "value"), row.names = c(NA, 10L), class = "data.frame")


uniq <- unique(dataSet$variable)
for (i in 1:length(uniq)){
     rowsPerVal <- dataSet[dataSet$variable == uniq[i], ]
     print(length(rowsPerVal))
}

我只是不明白最终的打印语句如何说长度为 3,当数据框中有 10 条记录具有相同的variable列值时。

4

2 回答 2

3

plyr也适用于这种拆分-应用-组合问题(将数据设置为块,对每个块进行操作,然后重新组合在一起)。

library("plyr")
ddply(dataSet, .(variable), nrow)

正如其他人所说length(), adata.frame是列数;nrow()是行数。

> ddply(dataSet, .(variable), nrow)
  variable V1
1     act1 10

您可以替换nrow为执行您想要的任何处理的(匿名)函数。

于 2013-05-08T21:22:14.593 回答
1

duplicated仅对第 2+ 个条目返回 TRUE。所以你可以用它来索引你的行:

dataSet[duplicated(dataSet$variable),] 

您还可以分配给他们:

dataSet[duplicated(dataSet$variable),]$value <- NA 
> dataSet
       DAY variable value
1  Tuesday     act1    67
2  Tuesday     act1    NA
3  Tuesday     act1    NA
4  Tuesday     act1    NA
5  Tuesday     act1    NA
6  Tuesday     act1    NA
7  Tuesday     act1    NA
8  Tuesday     act1    NA
9  Tuesday     act1    NA
10 Tuesday     act1    NA

要“吐出一个包含所有已处理行的新数据框”,您可以随意处理子集的 data.frame:

newDF <- transform( dataSet[duplicated(dataSet$variable),], DAY=sub("esd","foo",DAY) )
于 2013-05-08T20:35:09.303 回答