从CET时间到当地时间

时间:2015-07-21 15:11:48

标签: r if-statement

我有这个数据

> 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

我希望用当地时间创建一个变量$ hour。对话如下:从CET到本地时间的变化是

  

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

我尝试用嵌套的IF做到这一点。没有成功。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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), ]

将零替换为零:

full[is.na(full)] <- 0