我有这些数据
> 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.英国-1。BR-5
我试着用嵌套的IF来做。没能挺过来。
发布于 2015-07-21 15:33:36
#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发布于 2015-07-21 15:46:45
基本包:
# 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)] <- 0https://stackoverflow.com/questions/31543015
复制相似问题