[英]How to assign a unique number based on multiple columns in R dataset?
我收集了一些數據,這些數據在年、月、級別上都是不同的。 我想單獨為這三列的每一行分配一個唯一代碼(簡單數字)。 關於如何進行的任何建議?
year <- c("A","J","J","S")
month <- c(2000,2001,2001,2000)
level <- c("high","low","low","low")
site <- c(1,2,3,3)
val1 <- c(1,2,3,0)
df <- data.frame(year,month,level,site,val1)
#Result desired
df$Unique.code --> 1,2,2,3
dplyr
有cur_group_id()
function:
df %>%
group_by(year, month, level) %>%
mutate(id = cur_group_id())
# # A tibble: 4 × 6
# # Groups: year, month, level [3]
# year month level site val1 id
# <chr> <dbl> <chr> <dbl> <dbl> <int>
# 1 A 2000 high 1 1 1
# 2 J 2001 low 2 2 2
# 3 J 2001 low 3 3 2
# 4 S 2000 low 3 0 3
或者我們可以將一個factor
強制轉換為基數中的integer
:
df$group_id = with(df, as.integer(factor(paste(year, month, level))))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.