【问题标题】:Creating a variable that is the value of the fifth of another variable, and if no value on fifth period, takes the closest创建一个变量,它是另一个变量的第五个值,如果第五个周期没有值,则取最接近的
【发布时间】:2021-08-12 19:04:21
【问题描述】:

我需要帮助在以下数据集中创建变量“NewVar”:

df2 <- read.table(
text =
"Year,Data,Country,NewVar,
1,3,US,NA,
3,NA,US,NA,
5,2,US,2,
7,7,US,NA,
10,NA,US,7,
1,3,UK,NA,
2,5,UK,NA,
3,4,UK,NA,
5,NA,UK,4,
10,6,UK,6,
", sep = ",", header = TRUE)

换句话说,一个变量,它根据年份和国家获取“数据”的第五个值。 如果该国家/地区在该特定时期内不存在任何值,则它将采用该国家在过去 5 年间隔内最接近的值。

提前谢谢你!

【问题讨论】:

  • 您能多解释一下您希望输出的样子吗?顺便说一句,我从你的数据集中得到了一个额外的变量X
  • 对于变量 X,我深表歉意。这是一个错字。输出变量 NewVar 将采用另一个变量的每五个值。换句话说,使名为 Data quinquennial 的列。但是由于数据有限,可能不存在每 5 年的数据,因此必须取该国家最近一年的值。最好是第 5 年,如果没有,最好是第 4 年,依此类推。

标签: r dataframe regression economics


【解决方案1】:

解决此问题的一种方法是用以前的非缺失值补充缺失的数据。 {tidyr} 包有一个很好的 fill() 函数。

为了演示它的工作原理,我将结果存储在 Data2 和 NewVar2 中。随意覆盖您现有的列。

library(dplyr)
library(tidyr)

df2 %>% 
#------------ prepare the df, remove X and copy Data to Data2
  select(-X) %>% mutate(Data2 = Data) %>% 

#------------ use tidyr's fill to complement Data2
#------------ as we are interested in previous non-missing, use .direction="down"
  fill(Data2, .direction = "down") %>% 

#------------ check now every 5th year, if you need more %in% gives you freedom
  mutate(NewVar2 = case_when(
          Year %in% c(5, 10, 15) & !is.na(Data) ~ Data    # if value exists, take it
        , Year %in% c(5, 10, 15) & is.na(Data)  ~ Data2   # if not take alternative
        , TRUE ~ as.integer(NA))                          # set case_when default to NA
 )

这给了你:

   Year Data Country NewVar Data2 NewVar2
1     1    3      US     NA     3      NA
2     3   NA      US     NA     3      NA
3     5    2      US      2     2       2
4     7    7      US     NA     7      NA
5    10   NA      US      7     7       7
6     1    3      UK     NA     3      NA
7     2    5      UK     NA     5      NA
8     3    4      UK     NA     4      NA
9     5   NA      UK      4     4       4
10   10    6      UK      6     6       6

【讨论】:

    猜你喜欢
    • 2019-05-13
    • 1970-01-01
    • 2022-12-06
    • 1970-01-01
    • 2021-06-17
    • 2021-12-17
    • 2021-12-04
    • 1970-01-01
    • 2017-04-05
    相关资源
    最近更新 更多