簡體   English   中英

Dataframe 在 R 中的操作 - 根據行值編號為第 n 行分配一個值

[英]Dataframe manipulation in R - Assign a value to nth row based on row values numbers

我有這個例子 dataframe “df”:

id <- c(1001, 1002)
col2 <- c(5, 2)
col3 <- c(1, 4)
df <- data.frame(id, col2, col3)

有沒有一種簡單的方法可以轉換此數據框,使新數據框包含相同的列名,但將“1”分配給對應於每個值的第 n 行,並將“0”分配給剩余的槽位? 這似乎可行但有些困難。 結果表如下 (df_results):

id <- c(rep(1001, 5), rep(1002, 5))
col2 <- c(0,0,0,0,1, 0,1,0,0,0)
col3 <- c(1,0,0,0,0,0,0,0,1,0)
df_results <- data.frame(id, col2, col3)

您可以使用 cols 的並行最大值uncount() ,然后按 id 分組,檢查值是否等於行號:

library(dplyr)
library(tidyr)

df %>%
  uncount(pmax(col2, col3)) %>%
  group_by(id) %>%
  mutate(across(starts_with("col"), ~ as.numeric(.x == row_number()))) %>%
  ungroup()

# A tibble: 9 × 3
     id  col2  col3
  <dbl> <dbl> <dbl>
1  1001     0     1
2  1001     0     0
3  1001     0     0
4  1001     0     0
5  1001     1     0
6  1002     0     0
7  1002     1     0
8  1002     0     0
9  1002     0     1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM