2015-07-21 42 views
0

我有這樣的數據從CET時間爲當地時間

> dff_all[1:10,c(2,3)] 
    cet_hour_of_registration country_id 
1      20   SE 
2      12   SE 
3      11   SE 
4      15   GB 
5      12   SE 
6      14   BR 
7      23   MX 
8      13   SE 
9       1   BR 
10      9   SE 

,我想創建一個變量$小時,當地的時間。對話如下從CET到當地時間的變化是

FI + 1。 MX-7。 UK-1。 BR-5。

我試圖用一個嵌套的IF做到這一點。沒有做到。

+0

你可以編輯數據到問題:'dput(dff_all)'它可以讓它更容易運行。 – vinchinzu

回答

0
#Create a data lookup table 
country_id <- c("FI", "MX", "UK", "BR", "SE") 
time_diff <- c(1,-7,-1,-5, 0) 

df <- data.frame(country_id, time_diff) 


#this is a substitute data frame for your data. 
hour_reg <- c(20,12,11,15,5) 

dff_all <- data.frame(country_id, hour_reg) 

#joing the tables with dplyr function -> or with base join (double check join type for your needs) 
library(dplyr) 
new_table <- join(dff_all, df) 

#make new column 
mutate(new_table, hour = hour_reg - time_diff) 



    #output 
country_id hour_reg time_diff hour 
1   FI  20   1 19 
2   MX  12  -7 19 
3   UK  11  -1 12 
4   BR  15  -5 20 
5   SE  5   0 5 
0

基礎包:

# A variation of the example provided by vinchinzu 

# Original table 
country_id <- c("FI", "MX", "UK", "BR", "SE", "SP", "RE") 
hour_reg <- c(20, 12, 11, 15, 5, 3, 7) 
df1 <- data.frame(country_id, hour_reg) 

# Lookup table 
country_id <- c("FI", "MX", "UK", "BR", "SE") 
time_diff <- c(1, -7, -1, -5, 0) 
df2 <- data.frame(country_id, time_diff) 

# We merge them and calculate a new column 
full <- merge(df1, df2, by = "country_id", all.x = TRUE) 
full$hour <- full$hour - full$time_diff 
full 

輸出,在情況下,我們沒有那個國家的查找表,我們將得到NA:

country_id hour_reg time_diff hour 
1   BR  15  -5 20 
2   FI  20   1 19 
3   MX  12  -7 19 
4   RE  7  NA NA 
5   SE  5   0 5 
6   SP  3  NA NA 
7   UK  11  -1 12 

如果我們想顯示所有沒有NA的行:

full[complete.cases(full), ] 

用NA代替零:

full[is.na(full)] <- 0 
相關問題