如何在r中创建一个数字变量来表示该对每年出现的次数?

bqujaahr  于 2023-03-15  发布在  其他
关注(0)|答案(2)|浏览(118)

我想在下面的df3中创建一个变量"whatiwant"
虽然我通常使用add_count,但add_count将总计数值放入变量中,因此它不适用于这种情况。

df1 <- data.frame(exporter = c("Laos", "Brazil", "USA"),
                  product = c("apple", "banana", "orange"),
                  year = 2010,
                  whatiwant = 1)

df2 <- data.frame(exporter = c("Laos", "Brazil", "Israel"),
                  product = c("apple", "banana", "grape"),
                  year = 2011,
                  whatiwant = c(2, 2, 1))

df3 <- rbind(df1, df2)
iq3niunx

iq3niunx1#

我们可能需要rowid

library(data.table)
library(dplyr)
df3 %>%
    mutate(whatIwant2 = rowid(exporter, product))
  • 输出
exporter product year whatiwant whatIwant2
1     Laos   apple 2010         1          1
2   Brazil  banana 2010         1          1
3      USA  orange 2010         1          1
4     Laos   apple 2011         2          2
5   Brazil  banana 2011         2          2
6   Israel   grape 2011         1          1

或者使用base R

df3$whatIwant2 <- with(df3, ave(seq_along(exporter), exporter, 
     product, FUN = seq_along))
h7appiyu

h7appiyu2#

使用dplyr,您可以按exporterproduct的组使用row_number()

library(dplyr)

df3 %>%
  mutate(whatIwant2 = row_number(), .by = c(exporter, product))

#   exporter product year whatiwant whatIwant2
# 1     Laos   apple 2010         1          1
# 2   Brazil  banana 2010         1          1
# 3      USA  orange 2010         1          1
# 4     Laos   apple 2011         2          2
# 5   Brazil  banana 2011         2          2
# 6   Israel   grape 2011         1          1

相关问题