2015-04-04 106 views
-1

因此,我有一个很大的数据集,有许多列(10)和100,000行。其中一列是观察日期,另外还有两个相应的栏目,一个种类和另一个年份。首先,我想创建一个新列,这将为我提供观测前10%(每年每种物种)每年每种物种的平均观察日期。其次,我想减少该数据集,以便只保留计算中涉及的行(即:前10%)。最后,重要的是,我的新数据集有其他相应的列,每个观察的信息,即位置等。 样本数据集的(确实存在更多的列):R:减少数据集并创建条件平均值

date=c(3,84,98,100,34,76,86...) 
species=c(blue,purple,grey,purple,green,pink,pink,white...) 
id=c(1,2,3,2,4,5,5,6...) 
year=c(1901,2000,1901,1996,1901,2000,1986...) 
habitat=c(forest,plain,mountain...) 

实例:在第一行说种蓝色被认为在森林中的1901年1月3日。

+1

data.table和dplyr都是用于此类操作的良好软件包。请参阅http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – 2015-04-04 19:02:15

+0

我真的很可怕的R,任何想法我会如何使用dplyr具体? – John 2015-04-04 21:02:05

回答

0

好的,这里有一个使用dplyr的方法。这将为您提供变量的平均值,按物种和年份计算,每个分组使用前10%的观察值。

require(dplyr) 

# test data set 
test <- data.frame(species = c(rep("blue", 100), rep("purple",100)), 
        year = rep(c(1901, 1902, 1903, 1904, 1905), 40), 
        value = rnorm(200), 
        stringsAsFactors = FALSE) 

# checking data set 
group_by(test, species, year) %>% summarise(n = n(), mean.value = mean(value)) 

# by species and year, identify first ten per cent of observations 
test <- test %>% group_by(species, year) %>% 
    mutate(nth.ob = seq_along(species), n.obs = n(), pc = round((nth.ob/n.obs*100), 2)) %>% 
    arrange(species, year) # sort for easy viewing 

# and check 
head(test) 
Source: local data frame [6 x 6] 
Groups: species, year 

    species year  value nth.ob n.obs pc 
1 blue 1901 -0.2839094  1 20 5 
2 blue 1901 -1.7158035  2 20 10 
3 blue 1901 1.1664650  3 20 15 
4 blue 1901 -0.0935940  4 20 20 
5 blue 1901 -0.1199253  5 20 25 
6 blue 1901 0.3461677  6 20 30 

# reduce to top 10 %, summarise and drop unwanted variables 
out <- test %>% 
    filter(pc <= 10) %>% # select first 10% of observations by species and year 
    summarise(mean_val = mean(value)) 
out 


Source: local data frame [10 x 3] 
Groups: species 

    species year mean_val 
1  blue 1901 -0.99985643 
2  blue 1902 0.08355729 
3  blue 1903 0.67396796 
4  blue 1904 0.14425229 
5  blue 1905 -0.19426698 
6 purple 1901 0.95767665 
7 purple 1902 -0.40730494 
8 purple 1903 0.10032964 
9 purple 1904 0.36295224 
10 purple 1905 1.30953008 

如果你那么想在其中检测第一次观测的设置,我想做到这一点的最好办法是做类似

setting <- group_by(species, year) %>% 
    filter(row_number() == 1) 

,然后加入到数据到out数据集