1

I have a table test.csv with column

X
1 
1 
1 
2 
2 
5 
5 
5 
5

I want to compare each element in column X with 1 (in this case I have 3 matches)

I want to count the number and print output in a new file output.txt as follows

[c1]

1   2 3

Next each X column element with 2 (here 2 matches)

Want to append the result to output.txt

[c1]
1  2  3
[c2]
4  5

Next each element in column X with 5 (4 matches are there)

So final output.txt is

[c1]
1  2  3
[c2]
4  5
[c3]
6 7 8 9

My current table contains 750 elements in a column. I want to create an output as I state in the above example. Can I use for loop or multiple conditional loop?

Bikash
  • 11
  • 2
  • Is this something different from the [question you asked yesterday](https://stackoverflow.com/questions/48858889/how-to-compare-an-element-in-a-table-using-r-programming)? – Ronak Shah Feb 20 '18 at 05:18
  • Yes. The previous question was confusing due to unnecessary X column data. I need to use looping to solve the problem as I have few hundreds of data in a single column. – Bikash Feb 20 '18 at 05:23
  • `split(1:length(x),x)` – Onyambu Feb 20 '18 at 05:48

2 Answers2

0

It took me a few read throughs, you're after the position of each item

x <- c(1,1,1,2,2,5,5,5,5)
for (n in unique(x)) {
  print(paste(as.character(n), " was found at:"))
  print(which(x %in% n, arr.ind = TRUE))
}

It's probably a better idea to write out as .csv file for storage.

Amar
  • 1,340
  • 1
  • 8
  • 20
  • 1
    To save the results of this loop in an output text file, replace the `print` functions by `cat(..., file = "output.txt", append = TRUE)` and it will echo it straight in `"output.txt"`. For totally matching the question, you can replace `paste(as.character(n), " was found at:")` by `paste0("[c", n, "]")`. – Thomas Guillerme Feb 20 '18 at 05:55
  • Good addition. I was a bit lazy because the post was a bit confusing for myself. So I left it simple. – Amar Feb 20 '18 at 06:03
0

To be honest I find this question a bit confusing, since you lack column Y. However here is how you can get number of occurrences if this is what you want by one-liner:

aggregate(data.frame(count = data$X), list(value = data$X), length)

and a for loop

uvals <- unique(data$X)
result <- matrix(data = NA, nrow = length(uvals), ncol = 2)
colnames(result) <- c("val", "count")
for(i in 1:length(uvals)) {
    result[i, 1] <- uvals[i]
    result[i, 2] <- sum(data$X == uvals[i])
}

I would also recommend to do the calculations first and then write to a file.

Aleh
  • 776
  • 7
  • 11