What code to use in R 3.5.1 to count numbers of unique var2 for each unique var1?
Clash Royale CLAN TAG#URR8PPP
What code to use in R 3.5.1 to count numbers of unique var2 for each unique var1?
I have a data with 2 columns. Var1 - school classes, Var2 - names of students in the class. What command can I use to make a new matrix that will show how many times are repeated unique names in var2 for each unique var1?
Var1 Var2
9 Sarah
9 John
12 Sarah
11 Veronica
10 John
10 John
11 Veronica
12 John
12 Veronica
11 Veronica
10 Sarah
9 Veronica
9 John
What command can I use to make a new matrix that will show how many times are repeated unique names in var2 for each unique var1?
_____Sarah____Veronica__John
9______1_______1___________2
10_____1_______0___________1
11_____0_______3___________0
12_____1_______1___________1
Thank you in advance!
2 Answers
2
You need the table function
var1 <- c(9, 9, 12, 11, 10, 10, 11, 12, 12, 11, 10, 9, 9)
var2 <- c("Sarah", "John", "Sarah", "Veronica", "John",
"John", "Veronica", "John" ,"Veronica",
"Veronica", "Sarah", "Veronica", "John")
table(var1, var2)
You want a contigency table:
df <- data.frame(Var1, Var2)
xtabs(~Var1 + Var2, df)
# Var2
#Var1 John Sarah Veronica
# 9 2 1 1
# 10 2 1 0
# 11 0 0 3
# 12 1 1 1
To count the number of unique combinations, you can use subset to remove the duplicates, and then calculate the column sums:
z <- xtabs(~Var1 + Var2, df, subset=!duplicated(df))
colSums(z)
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
table(df$Var1,df$Var2)
– A. Suliman
Aug 6 at 17:00