简体   繁体   中英

Assigning the number in new column based on row count

I would like to know how to increase number based on whether in every 10 row.

For example

test_table <- data.frame(row=c(rev(0:99)))

        > head(test_table,11)
   row
1   99
2   98
3   97
4   96
5   95
6   94
7   93
8   92
9   91
10  90
11  89

I want to add new column when we passed every 10nth row in row column.

So I tried

library(dplyr)
 test_table%>%
   mutate(No=cumsum(n()/10==10))

which gives every No column to be 1 . What I look for is the number incrasing from 0,1,2,3 in every 10 row change in data. How can I do that ?

        row No
1    99  1
2    98  1
3    97  1
4    96  1
5    95  1
6    94  1
7    93  1
8    92  1
9    91  1
10   90  1
11   89  1

expected output

   row No
1    99  0
2    98  0
3    97  0
4    96  0
5    95  0
6    94  0
7    93  0
8    92  0
9    91  0
10   90  0
11   89  1

You can do a modular division on row_number :

test_table %>% mutate(No = (row_number() - 1) %/% 10)

#    row No
#1    99  0
#2    98  0
#3    97  0
#4    96  0
#5    95  0
#6    94  0
#7    93  0
#8    92  0
#9    91  0
#10   90  0
#11   89  1
# ...

You can try using floor after dividing row_number() by 10 . This will increase the No at every 10th row:

library(dplyr)

test_table <- data.frame(row=c(rev(0:99)))

test_table%>%
  mutate(No=floor((row_number()-1)/10))

#     row No
# 1    99  0
# 2    98  0
# 3    97  0
# 4    96  0
# 5    95  0
# 6    94  0
# 7    93  0
# 8    92  0
# 9    91  0
# 10   90  0
# 11   89  1
# 12   88  1
# 13   87  1
# 14   86  1
# 15   85  1
# 16   84  1
# 17   83  1
# 18   82  1
# 19   81  1
# 20   80  2
# 21   79  2
#......so on

Here is a base R solution.

test_table$No <- (seq_len(nrow(test_table)) - 1) %/% 10

head(test_table, 15)
#    row No
# 1   99  0
# 2   98  0
# 3   97  0
# 4   96  0
# 5   95  0
# 6   94  0
# 7   93  0
# 8   92  0
# 9   91  0
# 10  90  0
# 11  89  1
# 12  88  1
# 13  87  1
# 14  86  1
# 15  85  1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM