0

Currently, I am trying to go through a select few columns of a database. The columns contain part numbers and some part names need to be removed before put into a vector. I am able to do this for one column using the following loop. However, I want to be able to go through all the columns I want without having to copy the loop for each column.

Ordered = NULL

for (i in x1$V4) {
   if (i != as.character("PartX")) #if statement of i is not equal to PartX
   Ordered[i] <- i #puts i in new vector
}

z=data.frame(table(Ordered))

I want to be able to create a table for all of the part numbers using table. I tried to do this through apply but didn't work well. I know this code works I just need to expand it over multiple columns.

This is what my dataset currently looks like.

#   V4   V5    V6    V7    V8
# PartA PartE PartC PartX PartX
# PartC PartX PartX PartX PartX
# PartF PartB PartE PartD PartA
# PartE PartA PartC PartX PartX
# PartA PartE PartD PartX PartX
# PartB PartA PartC PartF PartX

This is what I want my newest vector/dataset to end up like.

#   V1
# PartA
# PartC
# PartF
# PartE
# PartA
# PartB
# PartE
# PartB
# PartA
# PartE
# PartA
# PartC
# PartE
# PartC
# PartD
# PartC
# PartD
# PartF
# PartA
Lara
  • 1
  • 1
  • 3
    Welcome to Stack Overflow! Please supply some sample data, e.g., using `dput` in order to make this [a reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). – Thomas Feb 26 '14 at 21:23
  • The for-loop is almost certainly not the best way to do this in R, but as Thomas said we need to see an example of the data you are working with. – Ista Feb 26 '14 at 21:29
  • Hi Thomas and lsta! I updated it to add what kind of table I have and what I am looking for. I hope this is better! Thank you in advance for your help! – Lara Feb 27 '14 at 15:10

1 Answers1

0

This will count all the parts (excluding PartX, or at least, returning 0 for that one, but really, you could just leave it in). This is using a version of x1 with 5 columns and 6 potential parts including "PartX":

do.call(cbind, lapply(x1, function(col) table(col[col != "PartX"])))

#       V1 V2 V3 V4 V5
# PartA  1  0  2  1  1
# PartB  2  2  2  1  0
# PartC  1  3  3  3  1
# PartD  3  0  1  1  3
# PartE  0  4  0  4  5
# PartX  0  0  0  0  0    

We used this as an input:

#       V1    V2    V3    V4    V5
# 1  PartB PartB PartX PartC PartE
# 2  PartC PartB PartB PartD PartD
# 3  PartD PartE PartD PartC PartE
# 4  PartX PartC PartA PartB PartD
# 5  PartB PartE PartB PartE PartD
# 6  PartX PartC PartC PartE PartE
# 7  PartX PartE PartA PartE PartA
# 8  PartD PartX PartC PartA PartC
# 9  PartD PartC PartX PartE PartE
# 10 PartA PartE PartC PartC PartE

Which was generated by:

set.seed(1)
vals <- c(paste0("Part", LETTERS[1:5]), "PartX")
x1 <- setNames(
  as.data.frame(
    replicate(5, factor(sample(vals, 10, r=T), levels=vals), simplify=F)
  ), 
  paste0("V", 1:5)
)
BrodieG
  • 51,669
  • 9
  • 93
  • 146