0

我有一个包含约 1 百万行和 8 个列(变量)的大型数据集。其中一个变量 ORDER 的类别从 1 到 90。我想创建一个新的 data.frame,减少变量 ORDER (4) 1、2、3+ 和 ALL 的类别,其中 ALL 是总和所有类别 (1-90) 和 3+ 的频率是类别 >=3 的频率之和(所以 3 到 90)。

YEAR  PROVINCE  ZONA91OK AGE5 ORDER NATIONALITY_MOTHER NATIONALITY_FATHER FREQUENCY
 1979        1      101   15     1      No computable      No computable        10
 1989        3      102   20     1      No computable      No computable        50

我对 R 的数据管理非常陌生,因此非常感谢您对这个问题的任何帮助!

这是data.frame的示例

mydata<-structure(list(YEAR = c(1981, 1981, 1981, 1981, 1981, 1981, 1981, 
1981, 1981, 1981, 1981, 1981, 1981, 1981, 1981, 1981, 1981, 1981, 
1981, 1981, 1981), PROVINCE = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), ZONA91OK = c(101, 101, 101, 
101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 
101, 101, 101, 101, 101), AGE5 = c(15, 20, 20, 25, 25, 25, 25, 
30, 30, 30, 30, 30, 35, 35, 35, 35, 35, 35, 40, 40, 40), ORDER = c(1, 
1, 2, 1, 2, 3, 4, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 12, 1, 3, 5), 
NATIONALITY_MOTHER = structure(c(9L, 9L, 9L, 9L, 9L, 9L, 
9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L
), .Label = c("España", "UE-15 y PD", "Resto Europa", "Magreb", 
"África Sub-sahariana", "Latinoamérica", "Asia", "Resto del Mundo", 
"No computable"), class = "factor"), NATIONALITY_FATHER = structure(c(9L, 
9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 
9L, 9L, 9L, 9L, 9L), .Label = c("España", "UE-15 y PD", "Resto Europa", 
"Magreb", "África Sub-sahariana", "Latinoamérica", "Asia", 
"Resto del Mundo", "No computable"), class = "factor"), FREQUENCY = c(10, 
40, 20, 50, 30, 10, 1, 10, 15, 10, 1, 1, 5, 5, 5, 1, 1, 1, 
1, 1, 1)), .Names = c("YEAR", "PROVINCE", "ZONA91OK", "AGE5", 
"ORDER", "NATIONALITY_MOTHER", "NATIONALITY_FATHER", "FREQUENCY"
 ), row.names = 60175:60195, class = "data.frame")
4

1 回答 1

0

如果您的数据有 1M 行,您可能会想要使用data.table

library(data.table)
myDT <- data.table(mydata, key="ORDER")

specialCats <- c(1, 2, 3)

rbind(
    myDT[, list(SUM_FOR="ALL", FREQ_SUM=sum(FREQUENCY))]
  , myDT[!.(specialCats), list(SUM_FOR="3+", FREQ_SUM=sum(FREQUENCY))]
)

## RESULTS: 
       SUM_FOR FREQ_SUM
1:     ALL      219
2:      3+        7

更新回复:评论

要将ORDER列更改为您的要求,请使用:

myDT[, order := ifelse(ORDER %in% specialCats, as.character(ORDER), "3+")]

注意1:为了有3+一个值,你需要转换为字符串。
注 2:添加一行 for"ALL"没有多大意义,你会放什么 forAGEPROVINCE

于 2013-10-09T15:05:51.107 回答