如何向R中的向量添加缺少的值
我有两个向量。年份向量对应于观察到某些事件的年份。计数向量列出了相应年份观察事件的次数。例如,1940年观察到3起事件,1942年观察到4起事件,依此类推如何向R中的向量添加缺少的值,r,vector,R,Vector,我有两个向量。年份向量对应于观察到某些事件的年份。计数向量列出了相应年份观察事件的次数。例如,1940年观察到3起事件,1942年观察到4起事件,依此类推 year <- c(1940, 1942, 1944, 1945) count <- c(3, 4, 7, 2) 你知道如何做到这一点吗?你可以通过将向量转换成一个数据帧,并将其与一个新的数据帧进行合并,以获得完整的年份: year <- c(1940, 1942, 1944, 1945) count <- c(3,
year <- c(1940, 1942, 1944, 1945)
count <- c(3, 4, 7, 2)
你知道如何做到这一点吗?你可以通过将向量转换成一个数据帧,并将其与一个新的数据帧进行合并,以获得完整的年份:
year <- c(1940, 1942, 1944, 1945)
count <- c(3, 4, 7, 2)
df <- data.frame(year, count)
df <- merge(df, data.frame(year=seq(1940, 1945)), all.y=T)
df[is.na(df)] <- 0
如果您希望将数据作为向量而不是数据帧返回:
year <- df$year
count <- df$count
通常,最好将这些向量保存在数据帧中,然而,这里有一种处理向量的方法
newyear <- min(year) : max(year)
newcount <- count[match(newyear, year)]
newcount[is.na(newcount)] <- 0
newyear
#[1] 1940 1941 1942 1943 1944 1945
newcount
#[1] 3 0 4 0 7 2
你可以做:
year <- c(1940, 1942, 1944, 1945)
count <- c(3, 4, 7, 2)
#Include all years in the year new
year_new <- min(year):max(year)
#Initialize the new count to 0s
count_new <- rep(0, length(year_new))
#Update the places where previously a value existed with the old count value
count_new[year_new %in% year] <- count
作为我关于堆栈溢出的第一篇文章中已解决问题的尝试: 您也可以通过循环获得预期结果:
year <- c(1940, 1942, 1944, 1945)
count <- c(3, 4, 7, 2)
year_new <- seq(min(year),max(year),1) # Create new year vector as requested
count_new <- vector(mode="integer",length = length(year_new))
timer <- 1# to compare next element in the "count" vector
for (i in 1:length(year_new)){
if (year_new[i]==year[timer]){
count_new[i]=count[timer] #update "count_new"
timer <- timer+1 # update which element to select in "count"
}}
虽然这是一个非常缓慢和低效的代码,但该方法可以应用于大多数软件包
year <- c(1940, 1942, 1944, 1945)
count <- c(3, 4, 7, 2)
year_new <- seq(min(year),max(year),1) # Create new year vector as requested
count_new <- vector(mode="integer",length = length(year_new))
timer <- 1# to compare next element in the "count" vector
for (i in 1:length(year_new)){
if (year_new[i]==year[timer]){
count_new[i]=count[timer] #update "count_new"
timer <- timer+1 # update which element to select in "count"
}}