create
Thanks for the reprex. I think this is one way to do what you want: dt$flag2 <- 0 + with(dt,Item == "DESK" & check %in% code2)
dt$flag2 <- 0 + with(dt,Item == "DESK" & check %in% code2) dt
name Item check flag2 1 A DESK NORF 0 2 B RANGE GARRA 0 3 C CLOCK PALM 0 4 D DESK RR 1 5 E ALARM DESPRF 0 6 H DESK RF 1 7 K DESK CORR 0 8 K WARF CORR 0 9 G NONE RF 0 This uses: 1) logical coerced to numeric by 0 + ... construction , which is probably unnecessary: leave it as logical 2) ?"%in%" 3) ?with The first two are fairly basic and should be covered in most decent basic R tutorials. Spending some time with one or more will probably save you a lot of time and aggravation later. The with() function is somewhat more advanced, but can save lazy people (= me) a lot of typing hassle. Cheers, Bert Bert Gunter "The trouble with having an open mind is that people keep coming along and sticking things into it." -- Opus (aka Berkeley Breathed in his "Bloom County" comic strip )
On Wed, Jan 27, 2021 at 9:48 AM Val <valkremk at gmail.com> wrote:
Hi all, I have a sample of data as shown below,
dt <-read.table(text="name Item check
A DESK NORF
B RANGE GARRA
C CLOCK PALM
D DESK RR
E ALARM DESPRF
H DESK RF
K DESK CORR
K WARF CORR
G NONE RF ",header=TRUE, fill=T)
I want create another column (flag2) and assign a value 0 or 1
if the check column values are within code2 list and Item is DESK
then flag2 =1 otherwise 0
code2=c("RR","RF")
index2=grep(paste(code2,collapse="|"),dt$check)
dt$flag2=0
dt$flag2[index2]=1
How can I add the second condition?
Desired output is shown below
name Item check flag2
1 A DESK NORF 0
2 B RANGE GARRA 0
3 C CLOCK PALM 0
4 D DESK RR 1
5 E ALARM DESPRF 0
6 H DESK RF 1
7 K DESK CORR 0
8 K WARF CORR 0
9 G NONE RF 0
Thank you,
______________________________________________ R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.