【问题标题】:Randomly creating a var that is zero or one by group, and an additional variable (zero or one), if the variable was one随机创建一个按组为零或一的变量,以及一个附加变量(零或一),如果变量为一
【发布时间】:2020-06-29 16:15:58
【问题描述】:

我的样本数据如下:

panelID= c(1:50)
year= c(2005, 2010)
country = c("A", "B", "C", "D", "E", "F", "G", "H", "I", "J")
urban = c("A", "B", "C")
indust = c("D", "E", "F")
sizes = c(1,2,3,4,5)
n <- 2
library(data.table)
library(dplyr)
set.seed(123)
DT <- data.table(   country = rep(sample(country, length(panelID), replace = T), each = n),
                    year = c(replicate(length(panelID), sample(year, n))))
DT [, uniqueID := .I]                                                         # Creates a unique ID     
DT[DT == 0] <- NA 
DT$sales[DT$sales< 0] <- NA 
DT <- as.data.frame(DT)
DT <- DT %>%
group_by(country) %>%
mutate(base_rate = as.integer(runif(1, 12.5, 37.5))) %>%
group_by(country, year) %>%
mutate(tax_rate = base_rate + as.integer(runif(1,-2.5,+2.5)))

我想创建一个额外的变量Vote,对于每个国家/地区-年份对,它要么是 1 要么是 0。

然后是另一个变量 Vote_won,如果是 Vote==1,则为 1 或 0。

我试过了:

DT <- DT %>%
group_by(country, year) %>%
mutate(Vote = sample(c(0,1),3)) %>%
group_by(country, year) %>%
mutate(Vote_won = ifelse(Vote=1, sample(c(0,1),1),0))

但它说:

sample.int(length(x), size, replace, prob) 中的错误: 'replace = FALSE' 时不能抽取大于总体的样本

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    mutate 不会更改您的分组,因此您不必两次使用具有相同参数的group_by。删除第二个group_by-statement 可以合并两个mutate-functions: 因此

    DT %>%
      group_by(country, year) %>%
      mutate(Vote = sample(c(0,1),1) ,
             Vote_won = ifelse(Vote==1, sample(c(0,1),1),0))
    

    应该给你你正在寻找的东西。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-25
      • 2016-10-21
      • 1970-01-01
      • 1970-01-01
      • 2022-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多