0

I am a beginner in working with R and need some help. Sorry if this question was answered before.

1) I have following data.frame

ID  test
"1" "testA" 
"1" "testB" 
"2" "testA" 
"2" "testB" 
"3" "testA"
"4" "testB"

The data.frame provides information on whether test A and/or test B was performed in test subjects

2) I would like to combine the individual rows with the same ID into one single row without losing the information in "test". This is the desired output:

ID testA testB
1     1     1
2     1     1
3     1     0
4     0     1

with 1 = yes and 0 = no

Arslanbekov Denis
  • 1,674
  • 12
  • 26
Robby
  • 1
  • 1

1 Answers1

0

Suggested solution (in a deleted comment) with reshape():

dat <- read.table(textConnection("
ID test
1 A
1 B
2 A
2 B
3 A
4 B
"), header = TRUE, colClasses=c("character", "character"))

dat$value <- 1
dat <- reshape(dat, idvar = "test", timevar = "ID", direction = "wide")
dat[is.na(dat)] <- 0
dat <- t(dat[, 2:5])
dimnames(dat) <- list(1:4, c("A", "B"))
dat

Suggested solution (in a comment by @RonakShah) with table():

dat <- read.table(textConnection("
ID test
1 A
1 B
2 A
2 B
3 A
4 B
"), header = TRUE, colClasses=c("character", "character"))

table(dat)