简体   繁体   中英

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

I have id variable and date variable where there are multiple dates for a given id (a panel). I would like to generate a new variable based on whether ANY of the years for a given id meet a logical condition. I am not sure of how to code it so please don't take the following as R code, just as logical pseudocode. Something like

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

As an example:

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

Should return newvar 1 1 0 1

Since data[ID==1] contains A in some year, it should also ==1 in 2000 despite Letter==B that year.

Here's a solution using plyr :

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

Here's a way of approaching it with base 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

Without using a package:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM