I am new to R and I will try to be as clear as possible for my request.
I have a dataframe named data_count, which looks something like that:
A B C D
1 2 3 4
5 6 5 4
3 2 1 2
3 4 5 6
5 4 3 2
First of all I want to add how many times a certain value appears in two consecutive rows, and I want this to be done column by column. To do that, I have thought of looping through data_count in order to create dataframes of 2 consecutive rows (let's call them data_dynamic), on which I simply perform a count function. So this is roughly what happens:
for (i in 1:(nrow(data_count))){
limit <- i+1 # this is how I get the two rows
data_dynamic <- data[i:limit,] # this is how I get the 2-row dataframe
So far, all good. But now I want to count, within data_dynamic, how often the numbers 1,2,3,4,5 and 6 appear.
This is so I can write the following dataframe data_count2:
#1 #2 #3 #4 #5 #6
1 1 1 2 2 1
1 2 1 1 2 1
....
In which the first row tells you: "In the first two rows of data_count, the number 1 appears once, while the number 4 appears twice".
for (i in 1:(nrow(data_count))){
limit <- i+1
data_dynamic <- data[i:limit,]
for (k in 1:6){
count_example <- c(count_example,sum(data_dynamic == k)))
data_count2[,(k+1)] <- count_example
}
}
count_example should be supposed to be a column of data_count2.
For some reasons, this does not work. Can anyone help me? I've been struggling on it for a while, any help would be very much appreciated, thanks!
table(unlist(data_count[1:2,]))will get you the tallies for the first group of rows; if applied over whole data frame should give you all the numbers you are looking for.