簡體   English   中英

在[R]中,為組的每個值生成新變量

[英]In [R], gen new variable for each value of group

我有id變量和date變量,其中給定id(一個面板)有多個日期。 我想根據給定ID的年份中的任何年份是否滿足邏輯條件來生成一個新變量。 我不確定如何編碼,因此請不要將以下內容作為邏輯代碼作為R代碼。 就像是

foreach(i in min(id):max(id)) {
if(var1[yearvar[1:max(yearvar)]=="A") then { newvar==1}
}

舉個例子:

ID     Year     Letter
1     1999        A
1     2000        B
2     2000        C
3     1999        A

應該返回newvar 1 1 0 1

由於data[ID==1]在某年中包含A,因此即使Letter==B在那一年,它在2000年也應==1

這是使用plyr的解決方案:

library(plyr)
a <- ddply(dat, .(ID), summarise, newvar = as.numeric(any(Letter == "A")))
merge(ID, a, by="ID")

這是使用基數R進行處理的一種方法:

#Find which ID meet first criteria
withA <- unique(dat$ID[dat$Letter == "A"])

#add new column based on whether ID is in withA
dat$newvar <- as.numeric(dat$ID %in% withA)

#    ID Year Letter newvar
# 1  1 1999      A      1
# 2  1 2000      B      1
# 3  2 2000      C      0
# 4  3 1999      A      1

不使用包:

dat <- data.frame(
    ID = c(1,1,2,3),
    Year = c(1999,2000,2000,1999),
    Letter = c("A","B","C","A")
)
tableData <- table(dat[,c("ID","Letter")])
newvar <- ifelse(tableData[dat$ID,"A"]==1,1,0)
dat <- cbind(dat,newvar)

#  ID Year Letter newvar
#1  1 1999      A      1
#2  1 2000      B      1
#3  2 2000      C      0
#4  3 1999      A      1

暫無
暫無

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

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