簡體   English   中英

將 R 中的因子轉換為日期以創建虛擬變量

[英]convert factor to date in R to create dummy variable

我需要為數據集“縣”中的變量“日期”為“2020 年 4 月 11 日之前和之后”創建虛擬變量。 數據集中有一百多個日期。 我試圖用 as.date function 來隱藏從因子到日期的日期,但得到 NA。 你能幫忙找出我在哪里出錯嗎? 我保留了我創建的另一個虛擬變量以防萬一,如果它影響整體結果

counties <- read.csv('C:/Users/matpo/Desktop/us-counties.csv')
str(counties)
as.Date(counties$date, format = '%m/%d/%y')
#create dummy variables forNew York, New Jersey, California, and Illinois
counties$state = ifelse(counties$state == 'New Jersey' & 
               counties$state == 'New York'& counties$state == 'California' & 
               counties$state == 'Illinois', 1, 0)
counties$date = ifelse(counties$date >= "4/11/2020", 1, 0)

str output

 $ date  : logi  NA NA NA NA NA NA ...
 $ county: Factor w/ 1774 levels "Abbeville","Acadia",..: 1468 1468 1468 379 1468 1178 379 1468 979 942 ...
 $ state : num  0 0 0 0 0 0 0 0 0 0 ...
 $ fips  : int  53061 53061 53061 17031 53061 6059 17031 53061 4013 6037 ...
 $ cases : int  1 1 1 1 1 1 1 1 1 1 ...
 $ deaths: int  0 0 0 0 0 0 0 0 0 0 ...``

謝謝!

  1. 您的as.Date格式不正確,您應該使用"%Y"表示 4 位數年份。

  2. 您需要將值分配回 ( <- ) 以使值更改。

  3. "4/11/2020"只是一個字符串,如果您要比較日期,則需要將其轉換為日期 object。 您也可以避免在此處使用ifelse

嘗試:

counties$date <- as.Date(counties$date, format = '%m/%d/%Y')
counties$dummy <- as.integer(counties$date >= as.Date('2020-04-11'))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM