2017-06-22 6 views
0

私はRで、このデータセットを持っている:1つの列についてRの列をフィルタリングする方法は?

image

そして、私は「weather_description」で繰り返される値をフィルタ処理したい毎回それが起こります。ただし、データセット内で再度発生した場合は削除しないでください。この列にこの変数の値が繰り返されるたびに削除したいだけです。出力は次のようになります。

2015-01-0101:00:00 sky is clear 1420070400 
2015-01-0102:00:00 scattered clouds 1420074000 
2015-01-0104:00:00 sky is clear 1420081200 

Rでこれを行う簡単な方法はありますか?

+1

あなたは、単純なGROUP BYまたは3列にわたって明瞭にwan't。 Google dplyr。 – CodeMonkey

答えて

0

これは、集約とベースのソリューションです:

@CodeMonkeyあたり dplyrを使用して
aggregate(Time ~ .,df,head,1) 
0

df %>% 
mutate(grouper = cumsum(weather_description == lag(weather_description, default = first(weather_description)))) %>% 
group_by(grouper) %>% 
summarise(Time = first(time), 
      weather_description = first(weather_description), 
      timestamps = first(timestamps)) 
0

ベースrのこのソリューションは、あなたのために働く場合は私に知らせてください:

データ

df <- data.frame(Time = c(as.Date(16436),as.Date(16437),as.Date(16437),as.Date(16437), 
          as.Date(16437),as.Date(16438),as.Date(16438),as.Date(16438), 
          as.Date(16438),as.Date(16439),as.Date(16439),as.Date(16439)), 
       weather_description = c("sky is clear", 
             "scattered clouds")[c(1,2,2,2,2,2,2,2,2,1,1,1)]) 
df 
#   Time weather_description 
#1 2015-01-01  sky is clear 
#2 2015-01-02 scattered clouds 
#3 2015-01-02 scattered clouds 
#4 2015-01-02 scattered clouds 
#5 2015-01-02 scattered clouds 
#6 2015-01-03 scattered clouds 
#7 2015-01-03 scattered clouds 
#8 2015-01-03 scattered clouds 
#9 2015-01-03 scattered clouds 
#10 2015-01-04  sky is clear 
#11 2015-01-04  sky is clear 
#12 2015-01-04  sky is clear 

機能

weather_changes <- function(dat){ 
    # split by weather description 
    splitted <- split(dat, dat[,2]) 
    # for each, return only the first dates of a sequence 
    byweather <- lapply(splitted, function(x) x[-which(c(0,ifelse(diff(x[,1])<2,1,0))==1),]) 
    # combine to a single data.frame 
    newdf <- do.call(rbind, byweather) 
    # order by date 
    newdf <- newdf[order(newdf[,1]),] 
    # remove the messy row names 
    rownames(newdf) <- NULL 
    newdf 
} 
weather_changes(df) 
#  Time weather_description 
#1 2015-01-01  sky is clear 
#2 2015-01-02 scattered clouds 
#3 2015-01-04  sky is clear 
関連する問題